简体   繁体   中英

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. 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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