Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 546
Mike Flynn Avatar asked Aug 01 '13 00:08

Mike Flynn


People also ask

How do I set observable value in Knockout?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

What is applyBindings in Knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.

What is Ko observable in knockout JS?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.

How do you declare a ViewModel property as observable?

Syntax. You just need to declare ViewModel property with function ko. observable() to make it Observable.


1 Answers

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"); 
like image 162
RP Niemeyer Avatar answered Sep 19 '22 01:09

RP Niemeyer