curran / model

A functional reactive model library for interactive data visualization.
MIT License
314 stars 43 forks source link

when and onChange concept #7

Closed nehalgala closed 9 years ago

nehalgala commented 9 years ago

What is the difference between when and on('change')? When to use what?

curran commented 9 years ago

Hello,

The syntax of on('change:foo') is specific to Backbone, and Model.js does not use the change: part.

The main difference between when and on is that the callback to on is invoked synchronously, and the callback to when is invoked asynchronously (on the next tick of the JavaScript event loop). This means that if a property is changed more than once synchronously, like this:

model.x = 5;
model.x = 6;

then the on callback would be called twice, but the when callback would be called once. Also, when callbacks are not invoked when a property is not defined, whereas on callbacks are. For example, if you set model.x = null.

Also, the main purpose of when is to depend on multiple properties, whereas on can only listen for changes to a single property.