Observable array push multiple Objects in knockout.js

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)