user2873816
user2873816

Reputation: 179

How can I understand backbone syntax

I am learning backbone.js. I found the following code from backbone.js documentation.

 //cretaing class name as Sidebar with extends Backbone.Model class  
 var Sidebar = Backbone.Model.extend({
                promptColor:function() {
                    var cssColor = prompt("Please enter a CSS color:");
                    this.set({color1: cssColor});
                }
        });
  //cretaing object for Sidebar class
        var sidebarObject = new Sidebar();
  //following statement not understand
        sidebarObject.on("change:color1", function(model, color23) {
            $('#body1').css({background: color23})
        });

What I understand :

whenever attribute color1 will change automatically model('Slidebar') triggers sidebarObject.on().

What I didn't understand :

  1. we are passing 2 arguments names are model,color23 to second argument of the sidebarObject.on(). I didn't understand anything about that arguments.

2.As per my understanding model is Sidebar in my example.Is it right.

can anyone help me.

Thanks.

Upvotes: 0

Views: 808

Answers (1)

Akos K
Akos K

Reputation: 7133

Yes, your second assumption is correct, in the above example Sidebar is the Model.

There are 2 parameters being passed to the callback function:

  1. the model on which the event initially occurred
  2. the value being passed alongside with the event

Note that the sidebarObject listens only to 'color' change events. Such event is generated when you change that particular attribute of the model:

this.set({color1: cssColor});

Now, if you change the listener to:

sidebarObject.on("change:taste", function(model, color23) {
    $('#body1').css({background: color23})
});

it won't be fire anymore when this.set({color: cssColor}); is called, because it listens to 'taste' change:

this.set({taste: 'good'});

I've separated the above example into a fiddle so you can play with it: http://jsfiddle.net/CtzsR/1/

If you are new to this whole thing http://backbonetutorials.com/what-is-a-model/ is a site worth looking at.

I hope now it's clearer.

Upvotes: 2

Related Questions