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

后端 未结 4 1238
情歌与酒
情歌与酒 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:15

    I like the solution provided by @RP Niemeyer when all subscribers need to be ignored. However, for my case, I have an observable with 2-way bindings on a Select control. When using @RP Niemeyer, the Select control isn't updated. So, I really needed a way to turn off specific observers, not all. Here is a generalized solution for this case.

    Add extensions methods for 'quiet' subscribe and 'quiet' writes.

    ko.observable.fn.ignorePokeSubscribe = function (callback, thisValue, event){
        var self = this;
        this.subscribe(function(newValue) {
            if (!self.paused)
                callback(newValue);
        }, thisValue, event);
        return this;
    };
    ko.observable.fn.poke = function (newValue) {
        this.paused = true;
        var result = this(newValue);
        this.paused = undefined;
        return result;
    };
    

    You would subscribe to observable like:

    this.name = ko.observable("Bob");
    this.name.ignorePokeSubscribe(function(newValue) { /* handler */ }));
    

    Then you would update it without specific notifications by doing:

    this.name.poke("Ted");   // standard subscribers still get notified
    

提交回复
热议问题