Search code examples
knockout.jsknockout-2.0

Get new value of an observable in "beforeChange" subscription


I know there are solutions to get the new value of an observable in a subscribe event (after the actual change), but I was wondering if it's possible to access the new value of an observable in a "beforeChange" subscription.

Below is a snippet of the current version of Knockout (3.4.1) raising the beforeChange and afterChange subscription handlers with the old value and the new value respectively:

if (computedObservable.isDifferent(state.latestValue, newValue)) {
    if (!state.isSleeping) {
        computedObservable["notifySubscribers"](state.latestValue, "beforeChange");
    }

    state.latestValue = newValue;
    if (DEBUG) computedObservable._latestValue = newValue;

    if (state.isSleeping) {
        computedObservable.updateVersion();
    } else if (notifyChange) {
        computedObservable["notifySubscribers"](state.latestValue);
    }

    changed = true;
}

Apparently the newValue is available at "beforeChange" so I guess forking would be an option, but I'd prefer not to.

Is there any other solution to get this new value "beforeChange"?


Solution

  • Note: This answer is based on your comment to the question and not the original question.

    When an observable is changed, it calls a method on the observable called notifySubscribers, which does the actual notification and thus updates any computed observables, bindings, etc. that depend on that observable. If you want to do something before any of these notifications, you have a few options.

    1. As @user3297291 noted, use Ryan Niemeyer's protectedObservable.

    2. Subscribe to the observable right away, before any anything else subscribes to it. Subscribers are always called in order, so your code will always run before anything else.

    3. Override notifySubscribers to hook into the notification process (remember to call the previous method).

    4. Possibly for Knockout 3.5.0, there will be a spectate event that occurs before the change event.