0

嗨,我在学习 Knockout 方面投入了大量时间,并且已经到了我的应用程序中有许多属性并且需要使用映射插件的地步。

应该如何使用它似乎很容易,但我想错过一些东西,因为它不起作用。我创建了一个测试示例。这是我的代码:

 function vm() {
            var self = this;
            this.viewModel = {};
            this.getData = function() {
                $.getJSON('/api/Values/Get').then(data)
                    .fail(error);

                function data(ajaxData) {
                    console.log(ajaxData);
                    self.viewModel = ko.mapping.fromJS(ajaxData);
                    console.log(self.viewModel);
                }

                function error(jError) {
                    console.log(jError);
                }
            };
        };

        ko.applyBindings(new vm());     

这是我的html:

        <ul data-bind="foreach: viewModel">
        <li data-bind="text:FirstName"></li>
        <input type="text" data-bind="value: FirstName"/>
    </ul>
    <button data-bind="click : getData">Press me!</button>

我的 ajax 调用成功地从服务器检索到这些数据:

[
   {
     FirstName: "Madalina",
     LastName: "Ciobotaru",
     hobies: [
          "games",
          "programming",
          "hoby"
           ]
   },
   {
     FirstName: "Alexandru",
     LastName: "Nistor",
     hobies: [
        "games",
        "programming",
        "movies"
        ]
   }
]

似乎在调用 data 函数后,viewModel get 被转换为一个数组,但其中没有任何项目。

我究竟做错了什么?

4

1 回答 1

1

I have taken your expected server data and created a jsfiddle here. You needed to change the viewModel property to be an observable array, and change the way the mapping is performed.

Here is a version of your script that will work:

function vm() {
    var self = this;
    this.viewModel = ko.observableArray([]);
    this.getData = function() {
        $.getJSON('/api/Values/Get').then(data)
            .fail(error);

        function data(ajaxData) {
            console.log(ajaxData);
            ko.mapping.fromJS(ajaxData, {}, self.viewModel);
            console.log(self.viewModel);
        }

        function error(jError) {
            console.log(jError);
        }
    };
};

ko.applyBindings(new vm());  
于 2013-05-24T00:29:23.637 回答