简体   繁体   English

淘汰赛映射无法更新observableArray

[英]Knockout mapping couldn't update observableArray

I am trying to update observable array by mapping plugin but plugin doesn't update the observable array. 我正在尝试通过映射插件来更新可观察数组,但插件不会更新可观察数组。

var list = ko.observableArray([]);
ko.mapping.fromJS([{ id: 1 }], list);
console.log(list()); //It is always empty

The mapping plugin goes through the properties of the input object and updates the properties of the target viewmodel accordingly. 映射插件将遍历输入对象的属性,并相应地更新目标视图模型的属性。 However, an array has no properties (at least none that you are interested in mapping). 但是,数组没有属性(至少没有您对映射感兴趣的属性)。

Try this instead: 尝试以下方法:

var viewmodel = {
    list: ko.observableArray([])
};

ko.mapping.fromJS({
    list: [{ id: 1 }]
}, {}, viewmodel);

console.log(viewmodel.list());

Note that the second parameter to mapping.fromJS() is supposed to be the mapping options. 注意,mapping.fromJS()的第二个参数应该是映射选项。 Since we have no options, I pass {} . 由于我们没有选择,因此我通过了{} The third parameter is the mapping target. 第三个参数是映射目标。


Arrays are not meant to be passed to the mapping plugin. 数组不打算传递给映射插件。 You can update them directly, there is no point in using the mapping plugin for something that really is as trivial as: 您可以直接更新它们,对于真正微不足道的东西使用映射插件是没有意义的:

var list = ko.observableArray([]);
list([{ id: 1 }]);

If you intend to maintain an array of child viewodels, that's where the mapping options come in handy: 如果您打算维护一系列子视口,则可以在其中使用映射选项:

var viewmodel = {
    list: ko.observableArray([])
}

ko.mapping.fromJS({
    list: [{ id: 1 }]
}, {
    list: {
        // make items in the "list" property become ItemModel
        // instances that are recognized by their respective ID
        create: function(options) {
            return new ItemModel(options.data);
        },
        key: function(item) {
            return ko.unrwap(item.id);
        }
    }

}, viewmodel);

console.log(viewmodel.list());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM