Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable array push multiple Objects in knockout.js

Tags:

knockout.js

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

like image 432
Aj_sari Avatar asked May 12 '14 10:05

Aj_sari


People also ask

What is Ko observable in knockout JS?

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.

How do I sort knockout observable array?

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.


2 Answers

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.

like image 170
RajeshKdev Avatar answered Sep 18 '22 16:09

RajeshKdev


Try

ko.utils.arrayPushAll(self.StatesList, [model, model1]); 
like image 23
philipooo Avatar answered Sep 18 '22 16:09

philipooo