在这里,事件附加到该特定模型实例。所以同样不会触发任何其他实例的事件..
var appointment = new Appointment({id: 1}); <--- Event is triggered
var appointment1 = new Appointment({id: 2}); <--- Event is not triggered
appointment.on('change',function() {
console.log('its changed');
});
由于事件直接附加在模型的实例上。但是如果你在定义模型时做同样的事情,它会在模型的所有实例上触发同样的事情。
var Appointment = Backbone.Model.extend({
initialize: function() {
this.on('change', function() {
console.log('its changed')
});
}
});
现在对模型实例的任何更改都会触发一个事件。
var appointment = new Appointment({id: 1}); <--- Event is triggered
var appointment1 = new Appointment({id: 2}); <--- Event is triggered
如果您在视图上谈论相同的内容,那么传递给实例的模型通常会继续监听事件。如果有任何变化,那么将调用一个方法来改变视图的状态。
var View = Backbone.View.extend({
initialize: function() {
// Listening to the event on the model which when
// triggered will render the view again
this.listenTo(this.model, 'change', this.render);
},
render: function() {
// do something
}
});
var view = new View();
view.render();