7

Under the Explicitly Subscribing to Observables section of the Knockout documentation, there is a reference to an event parameter of the subscribe function, but the only two examples given on that page are change and beforeChange.

By way of example, I tried passing in "focus" as the third parameter but that didn't work. I'm not too surprised as "focus" is an event of a DOM Element rather than a knockout observable, but nonetheless it could theoretically have setup a subscription to the focus event for all elements bound to that observable.

Is there a list of all events that can be subscribed to manually using Knockout's observable.subscribe function?

ec2011
  • 570
  • 6
  • 20
  • 1
    The only two built in options are the `change` and `beforeChange`. These are the only "events" of ko.observables. You probably need the `event` binding is you want to setup on a "focus" event... – nemesv May 06 '14 at 13:41
  • 1
    @nemesv Thanks for explaining that. Why not add this as an answer rather than a comment? When you say the "only two built in options", does this mean that it's possible to add extra custom events on observables that could be subscribed to this way? If so is there an example somewhere that shows how to do this? – ec2011 May 06 '14 at 14:15
  • There's also `arrayChange` as explained in [Tracking array changes](https://knockoutjs.com/documentation/observableArrays.html#tracking-array-changes) – dizarter Aug 11 '21 at 15:38

1 Answers1

3

It make sens to use "event" binding in your case.

Because there are only two ways to notify subscribers of observable variable: beforeChange and change.

In knockoutJs code there is simple chain of if blocks which check if event is specified, and if event is equal to beforeChange. That's basically all logic which goes there, so no other events fired.


Part form knockoutJS which implements this logic:

  self["notifySubscribers"] = function(value, event) {
    if (!event || event === defaultEvent) {
      self._rateLimitedChange(value);
    } else if (event === beforeChange) {
      self._rateLimitedBeforeChange(value);
    } else {
      self._origNotifySubscribers(value, event);
    }
  };
Dmitry Zaets
  • 3,289
  • 1
  • 20
  • 33
  • Thanks. I didn't want to use the event binding but instead I'd rather use some of the techniques shown at http://knockoutjs.com/documentation/unobtrusive-event-handling.html – ec2011 May 06 '14 at 15:55