Mike Flynn Mike Flynn - 5 months ago 142
Javascript Question

Change observable but don't notify subscribers in knockout.js

Is there a way to ignore subscribers on a value change of the observable. Id like to change a value of an observable, but not execute it for the subscribers with knockout.js

Answer

Normally this is not possible or advisable, as it potentially allows things to get out of sync in the dependency chains. Using the throttle extender is generally a good way to limit the amount of notifications that dependencies are receiving.

However, if you really want to do this, then one option would be to overwrite the notifySubscribers function on an observable and have it check a flag.

Here is an extensions that adds this functionality to an observable:

ko.observable.fn.withPausing = function() {
    this.notifySubscribers = function() {
       if (!this.pauseNotifications) {
          ko.subscribable.fn.notifySubscribers.apply(this, arguments);
       }
    };

    this.sneakyUpdate = function(newValue) {
        this.pauseNotifications = true;
        this(newValue);
        this.pauseNotifications = false;
    };

    return this;
};

You would add this to an observable like:

this.name = ko.observable("Bob").withPausing();

Then you would update it without notifications by doing:

this.name.sneakyUpdate("Ted");
Comments