Knockout's mapping breaks observable arrays

断了今生、忘了曾经 提交于 2019-12-05 13:15:22
RP Niemeyer

The issue that you are seeing is based on the fact that the mapping plugin will create an observableArray if it is given an array. So, you are setting the value of the self.items observableArray equal to an observableArray (rather than just an array). So, it is wrapped an extra time.

Here is one way to do it:

var ViewModel = function () {
    var self = this;
    self.items = ko.mapping.fromJS([]);
    self.load = function () {
        ko.mapping.fromJS([
            { "name": "joey", "value": 1 },
            { "name": "anne", "value": 2 },
            { "name": "paul", "value": 3 },
            { "name": "mike", "value": 4 }
        ], self.items);
    };
    self.check = function () {
        alert(self.items().length);
    };
    self.total = ko.computed(function () {
        var total = 0, items = self.items();
        for (var i = 0; i < items.length; i++) {
            total += items[i].value();
        }
        return total;
    });
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);

So, you initialize the original observableArray using the mapping plugin, so it is ready to be updated. Then, on the update you call ko.mapping.fromJS with the updated data and the the mapped object to update.

The other minor change at that point was just to use value() in your computed observable now that it is an observable from the mapping plugin.

Sample here: http://jsfiddle.net/rniemeyer/3La5K/

Or you could try knockout-data-projections

It hanldes view model to js arrays mappings quite well!!

You need to pass your items observableArray to the mapping function so that it can map the new values into it.

Working solution here: http://jsfiddle.net/unklefolk/j9pdX/

self.load = function () {
    ko.mapping.fromJS([
        { "name": "joey", "value": 1 },
        { "name": "anne", "value": 2 },
        { "name": "paul", "value": 3 },
        { "name": "mike", "value": 4 }
    ], {}, self.items);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!