1.

How Can You Track Any Change In Model Attribute Value?

Answer»

All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function, we are going to bind a function call EVERYTIME we change the value of our attribute. In this case, if the name of our “person” changes, we will alert their NEW name. Syntax for attaching callback to change EVENT of attribute is this.on(“change”, function(model){});.

See the EXAMPLE below:

Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0
},
initialize: function(){
alert("Below we are attaching callback to change event of 'name' attribute");
this.on("change:name", function(model){
var name = model.get("name"); // 'Stewie Griffin'
alert("Changed my name to " + name );
});
}
});

var person = new Person({ name: "Thomas", age: 67});
person.set({name: 'Stewie Griffin'}); // This TRIGGERS a change and will alert()

All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function, we are going to bind a function call everytime we change the value of our attribute. In this case, if the name of our “person” changes, we will alert their new name. Syntax for attaching callback to change event of attribute is this.on(“change”, function(model){});.

See the example below:

Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0
},
initialize: function(){
alert("Below we are attaching callback to change event of 'name' attribute");
this.on("change:name", function(model){
var name = model.get("name"); // 'Stewie Griffin'
alert("Changed my name to " + name );
});
}
});

var person = new Person({ name: "Thomas", age: 67});
person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()



Discussion

No Comment Found