使用映射插件的Knockout和observablearrays

时间:2013-09-23 00:25:45

标签: json asp.net-mvc-4 knockout.js knockout-mapping-plugin knockout-mvc

当我第一次调用它时,下面的代码工作正常,但是在第二次调用中gridviewmodel变得混乱,所有数据都变得多余

$.ajax({
        url: 'rest service uri',
        type: 'GET',
        data: parameters,
        dataType: 'json',
        crossDomain: true,

        success: function (data) {

            function gridviewModel() {
                var self = this;
                self.items = ko.mapping.fromJS(data);
                self.columns = [
                    new column("Name", "name", "Asc"),
                    new column("URL", "name", "Asc"),
                    new column("Embargo Date", "name", "Asc"),
                    new column("Status", "name", "Asc"),
                    new column("Reviewer Name", "name", "Asc"),
                    new column("Approver Name", "name", "Asc")
                ];
            };


            ko.applyBindings(new gridviewModel());
}

我尝试使用removeAll()清除可观察数组,但它不适用于我。

有什么想法吗?

只是因为任何人可能在未来面临这个问题我通过在Knockout映射插件中调用ko.mapping.fromJS(data,gridviewModel.items)来设法修复它 完整代码是

var gridviewModel = {

        items: ko.mapping.fromJS([]),
        columns: [
                    new column("Name", "name", "Asc"),
                    new column("URL", "name", "Asc"),
                    new column("Embargo Date", "name", "Asc"),
                    new column("Status", "name", "Asc"),
                    new column("Reviewer Name", "name", "Asc"),
                    new column("Approver Name", "name", "Asc")
                ]
};

$(function () {
    ko.applyBindings(gridviewModel, document.getElementById("wip"));

});

希望这能解决别人的问题。

1 个答案:

答案 0 :(得分:0)

在阅读了淘汰赛映射插件的文档后,您的data对象应该是viewmode,而不是viewmodel中的属性。如果我是你,我会修改我的代码以使用以下内容:

          function gridviewModel() {
                var self = this;
                self.items = data;
                self.columns = [
                    new column("Name", "name", "Asc"),
                    new column("URL", "name", "Asc"),
                    new column("Embargo Date", "name", "Asc"),
                    new column("Status", "name", "Asc"),
                    new column("Reviewer Name", "name", "Asc"),
                    new column("Approver Name", "name", "Asc")
                ];
            };


            ko.applyBindings(ko.mapping.fromJS(new gridviewModel()));

这将按照文档指定的方式映射整个对象。