Monday, July 7, 2014

How Change Events Are Triggered In Backbone

I was having trouble understanding the various states that a given Backbone model, and all it's attributes, might be in. Specifically, how does an attribute change, and trigger the change event for that attribute. The change event isn't triggered when the model is first created, which makes sense because the model had to previous state. In other works, creating the model also creates a state machine for the model attributes. However, this can be confusing if you're adding a new attribute to a model.

Here's a really simple example that illustrates the various initial states for model attributes and how they're changed.

var MyModel = Backbone.Model.extend({
        defaults: {
            b: 2
    model = new MyModel( { a: 1 } );

Backbone.listenTo( model, 'change', function( m ) {
    console.log( m.changed );    

model.set( { a: 2 } );
model.set( { b: 3 } );
model.set( { d: 4 } );

The initial value of the a attribute is 1. This gets passed in through the model constructor. And it changes to 2 later on, triggering a change event. The initial value of the b attribute is 2, coming from the defaults object. This changes to 3 later on triggering a change event. Finally, we add the d attribute with a value of 4 — also triggering a change event. This last operation triggers a change event because the attribute value goes from undefined to 4.

So there's three separate types of attribute value transitions to consider with Backbone models. From initial value, from default value, and from undefined.

No comments :

Post a Comment