Update Knockout.js Observable from JSON

喜夏-厌秋 提交于 2019-11-28 21:32:18

Here are 3 ways you could do this ... found in this fiddle: http://jsfiddle.net/johnpapa/nfnbD/

1) Use the ko.utils.arrayPushAll function 2) use your own logic 3) Write your own function on observableArray

Details ...

1) If you use the ko.utils.arrayPushAll function you will need to call valueHasMutated too, because the array effectively gets overwritten with itself. The observability does not fire off unles you tell it that it changed. Here is how you could do that:

ko.utils.arrayPushAll(this.users(), dataFromServer);
this.users.valueHasMutated();

2) The second option is to write your own loop logic, essentially using the same code as the arrayPushAll function like this.

for (var i = 0, j = dataFromServer.length; i < j; i++)
this.users.push(dataFromServer[i]);

3) Create a function of your own on the observableArray, like this:

ko.observableArray.fn.pushAll = function(valuesToPush) {
        var items = this;
        for (var i = 0, j = valuesToPush.length; i < j; i++){
            items.push(valuesToPush[i]);
        }
        return items;
};

Though this code above will notify every time an item is added. So it might be better to add them all, then notify. This would be more efficient. Like this:

ko.observableArray.fn.pushAll = function(valuesToPush) {
    var underlyingArray = this();
    this.valueWillMutate();
    ko.utils.arrayPushAll(underlyingArray, valuesToPush);
    this.valueHasMutated();
    return this;
};

Then call it like this:

this.users.pushAll(dataFromServer);

I know this is quite an old post but I came across it and just thought I'd show another way to do this in knockout without creating your own pushAll for any future visitors.

You can use a push.apply in knockout on a observable array. This will allow you to push multiple elements from a server and only trigger one notification.

Example in JsFiddle

Edit: The further reading for anyone reading this who wants to know why to use push.apply instead of using push in a loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!