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

后端 未结 4 1242
情歌与酒
情歌与酒 2020-11-28 05:33

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.j

4条回答
  •  一个人的身影
    2020-11-28 06:34

    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");
    

提交回复
热议问题