Knock Me Out

Thoughts, ideas, and discussion about Knockout.js

Knockout 1.3 Release Candidate + a New Feature

| Comments

Update: Knockout 1.3 was eventually renamed to version 2.0

Just a quick note: the Knockout.js 1.3 release candidate is now available for testing. Barring any last-minute fixes, this should be the final version. Files are available from: https://github.com/SteveSanderson/knockout/tree/master/build/output.

Some links to 1.3 information:

Currently, I am working with Steve on documentation updates to <Knockoutjs.com> before a final release. Hopefully, it will be ready soon!

Controlling when to receive subscription notifications

There were was one feature added recently, which hasn’t been covered, that I wanted to briefly highlight. Knockout 1.3 now allows you to decide when you want to be notified before or after a value has changed when creating a manual subscription. The default behavior, as before, is that the subscription runs after the value has changed and passes the new value as the first argument.

When creating a manual subscription, you can now opt to have your code run before the value has changed and receive the previous value as the first parameter. To be notified before the value changes, the subscribe API now accepts a third parameter to specify an event name.

1
2
3
viewModel.price.subscribe(function(value) {
    this.history.push({ value: value, time: new Date() });
}, viewModel, "beforeChange");

If the event name is not passed, then it will default to change, which is consistent with the current behavior of manual subscriptions.

This can be useful to take action before a value has changed or to track changes to values. Previously, you could have accomplished this with a writeable dependentObservable in front of the actual observable, but this allows a more direct way to accomplish this type of action.

While change and beforeChange are the only events that Knockout uses itself, we are able to subscribe to custom events. We would couple this with the use of the notifySubscribers method on an observable to trigger messages for those events. This could be useful in certain scenarios where your application wants to delegate responsibilities to other components.

1
2
3
4
5
6
7
8
9
viewModel.price.subscribe(function(newValue) {
    if (!newValue) {
        this.price.notifySubscribers(null, "valueRemoved");
    }
}, viewModel);

viewModel.price.subscribe(function() {
    //react to the value being removed
}, viewModel, "valueRemoved");

As shown above, we can create an overall subscription to an observable that looks at its state and decides when to notify subscribers of any appropriate events. These could be chained together and allow us to create components that expose specific events to subscribers. Seems like a potentially useful feature to consider when creating a reusable library with Knockout.

Comments