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 StatesList
, I can not proceed further. How can I add them both.
see Below:
var model1 = jQuery.parseJSON(ko.toJSON(argsToPost)); var model = jQuery.parseJSON(ko.toJSON(self.StateModel));
i need to add both to my ObservableArray
self.StatesList.push(model); self.StatesList.push(model1);
This is inserting into different records, I want to insert both objects at the same time
Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.
Description. The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.
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.
Try
ko.utils.arrayPushAll(self.StatesList, [model, model1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With