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
Try
ko.utils.arrayPushAll(self.StatesList, [model, model1]);
We do have ko.utils.arrayPushAll(array, valuesToPush)
as a utility function that you can use. It is not available directly off of observableArrays though.
If you add your pushAll to observableArrays
, you would want to operate on the underlying array (this() in your case) and then call valueHasMutated()
on the observableArray
at the end. This will ensure that subscribers to the observableArray
are only notified once with the end result rather than with each push.
In KO core, it would need to call valueWillMutate()
beforehand as well.
The point was that I would not recommend using the code that you posted, as it will notify on every push, which can have a performance impact if you are pushing many items.
In core, we might do something like:
ko.observableArray.fn.pushAll = function(valuesToPush) {
var underlyingArray = this();
this.valueWillMutate();
ko.utils.arrayPushAll(underlyingArray, valuesToPush);
this.valueHasMutated();
return this; //optional
};
The same discussion happened between John Papa
and RP Niemeyer
. The link can be found here. Hence, posted only useful tips as an answer here.
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"