Observable array push multiple Objects in knockout.js

前端 未结 3 1225
时光取名叫无心
时光取名叫无心 2021-01-03 18:26

Is there any option in ko, which pushes multiple elements at same time?

I have two elements which needs to be inserted into a observable array called StatesLis

3条回答
  •  礼貌的吻别
    2021-01-03 19:01

    A pushAll function has been discussed on github, see e.g. this issue or this pull request. As far as I gather it has not made it into the main code yet.

    However you can easily achieve a push-all like so:

    var items = ko.observableArray();
    
    items.push.apply(items, [1, 2, 3, 4]);
    

    as commented by stalniy in the second reference. The downside of this is that knockout will notify the subscribers after every single item pushed.

    Alternatively,

    function concat(the_list, items_to_concat) {
        the_list.splice.apply(the_list, [the_list().length, 0].concat(items_to_concat));
    }
    

    thus making use of the observableArray's splice implementation, as suggested by brianmhunt on the same thread.

    BTW: I admit that I did not know this by heart, I simply googled "push many knockout"

提交回复
热议问题