0

I took a small code from backbone home site, and consoled the function, in this example, sidebar.on('change:color'), takes the function. but it requires two parameter, one is abiously we need that is 'color', and we defining the element inside the function, still why we giving another parameter as 'model' here, what that parameter does?

if i remove that parameter send only the color, the function doesn't work at all... any one help me to understand this?

sample function here:

var Sidebar = Backbone.Model.extend({
    promptColor : function(){
    var cssColor = prompt('Please enter a css color');
        this.set({color:cssColor});       
    }
});

window.sidebar = new Sidebar;

sidebar.on('change:color',function(model,color){ // what model parameter do here?
    console.log(model);
    $('#sidebar').css({
        background:color
    })
})

sidebar.set({color:'green'});
sidebar.promptColor();

when i console the model i got this:

d
_callbacks: Object
_changing: false
_escapedAttributes: Object
_pending: Object
_previousAttributes: Object
_silent: Object
attributes: Object
changed: Object
cid: "c1"
__proto__: x
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

1

Backbone is a Javascript MVC framework. (Unlike standard MVC, Backbone doesn't have controllers, instead it has collections).

The model you are receiving is a standard model from the MVC paradigm. Model's are the underlying data structures that hold the data that the user is working with.

When you do

sidebar.on('change:color', function(model, color) { 
   // some code here
});

you are attaching an event handler to the sidebar model. Specifically, you are saying that when the color attribute on this model changes, call the function. Since this event can and will trigger at a later point in time, Backbone passes the event handler function two arguments: the first is the model on which the event fired, and the second is the attribute that changed.

The arguments are passed in a specific order, that is model is the first argument, and the changed attribute is the second. Thus if you omit the model argument from your event handler function, the passed in model gets assigned to color, and color doesn't get assigned to any argument.

Recommended reading:

More about MVC and models
More about backbone models

Ayush
  • 41,754
  • 51
  • 164
  • 239
1

It is possible that you want to know which model was affected.

Consider a case where you are listening to an event on a collection instead. Which model's color value was modified? The model parameter tells you this.

Also, consider a case where the same handler is listening to "change:color" on multiple models. Again, you might want to know which model sent the event.

Just like in other event-driven environments, the "sender" is always passed along with the event data. model, in this case, is the sender.

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167