Search code examples
javascriptknockout.jsko.observablearray

Can you modify multiple entities in an observable array, but have Knockout fire only a single change notification?


I have an observable array from which I need to remove one item and add another. If I just call .remove(myItem) on the observable array and then push my new item onto it, Knockout will fire two change notifications for that array, but in this case I would rather see this as a single change, firing only one notification.

What I've done to accomplish this is that I take out the underlying array and keep it in a temporary variable, I then do the modifications to that temporary variable, and when I'm done I put the whole thing back into the observable array. Something like this (somewhat simplified from what I actually do):

vm.MyArray = ko.observableArray(["foo", "bar"]);

// Later when I need to alter the observable array, I do something like this    
var temp = vm.MyArray();
temp.splice(0, 1);
temp.push("some");
vm.MyArray(temp);

Though this accomplish my goal, it doesn't feel like the right way of doing it.

Is there a more proper way to make multiple changes to an observable array, but only have a single notification fired?

Update:

The reason I don't want two notifications fired is because I subscribe to changes on the array, and make an AJAX-request to load new data whenever it changes. Because of this, I don't want to fire unnecessary notifications. I don't want notifications to be fired until I'm "done" editing the array.


Solution

  • To achieve such behavior you should work with unwrapped observable array and then call valueHasMutated method:

    vm.MyArray = ko.observableArray(["foo", "bar"]);
    vm.MyArray().remove(myItem);
    vm.MyArray().push(newItem);
    vm.MyArray.valueHasMutated();