Reputation: 79
How to bind a change event to model from view to change name and display the changed name in view block.
Student = Backbone.Model.extend({
initialize: function(){
this.on("change:name", function(model){
var name = model.get("name");
alert("Changed my name to " + name );
});
}
});
var pe = new Student({ name: "sinduja", age: 20});
pe.set({name: 'shalini'});
Upvotes: 2
Views: 145
Reputation: 5208
Doesn't backbone trigger change events automatically on model.set?
You just have to register your view to the change event.
Student = Backbone.Model.extend({
initialize: function(){
//initialize variables
}
});
StudentView = Backbone.View.extend({
initialize: function(model) {
_.bindAll(this);
model.on("change:name",this.nameChanged)
},
nameChanged: function(evt) {
console.log("name changed", evt)
}
})
Usage:
var pe = new Student({ name: "sinduja", age: 20});
var sv = new StudentView(pe);
pe.set({name: 'shalini'});
Upvotes: 1
Reputation: 14314
I used to write my own custom stuff for reacting to bi-directional model/view changes, which is a bit of a maintenance pain. Then I found the plugin Backbone.ModelBinder.
It makes what you want to achieve stupidly easy. There are some good examples on the github readme page I linked you to so there's no point me giving any! If it seems a bit confusing at first I would say try your best to get it working as in the long run this plugin will save you countless hours, like it has for me.
Upvotes: 0