1

I have an observable and I attached subscriber to that using subscribe() method. How I can conditionally make that very subscriber to be notified when changing observable?

Meant, there are cases when changing observable I need that subscriber to be called, but also there are not.

Thanks

  • 1
    The subscribe is always called. Just put your conditional logic inside your callback to decide if you need to do anything. – PatrickSteele Apr 25 '14 at 12:11

1 Answers1

5

Like Patrick Steele said, subscribe is always called when you change the value of an observable. If you don't want to notify a particular subscriber you should check the condition in the subscriber.

If you want to update an observable without notifying any subscriber, you can have a look at Change observable but don't notify subscribers in knockout.js; here you'll find an observable extension which allows for the following:

this.name.sneakyUpdate("Ted");

A different solution would be to create a computed which contains the condition you want to check and then subscribe to that computed. If for example you'd only want to notify a subscriber only if an observable's value is higher than 5, you could do the following:

self.myObservableIsHigherThan5 = ko.computed(function() {
    return self.yourObservable() > 5;
};
self.myObservableIsHigherThan5.subscribe(function() {
    ...
});
Community
  • 1
  • 1
sroes
  • 14,663
  • 1
  • 53
  • 72