Backbone 是一个事件驱动的框架,它定义的每个对象都可以listenTo
或trigger
事件。这就是组件在 Backbone 应用程序中的通信方式(内置事件)。考虑到这一点,每次 aBackbone.Model
的属性发生变化时,都会触发一个change:[attribute-name]
事件。您可以将任意数量的函数绑定到此事件。
这是一个从实例化到显示的示例(此处为 jsFiddle):
var Item = Backbone.Model.extend({ urlRoot: '/welcome/item' });
var ItemView = Backbone.View.extend({
// Very minimal example template for an item
template: _.template('<a href="#/item/<%= id %>"> <%= price %> </a>'),
initialize: function() {
// Calls the views render on model change
this.listenTo( this.model, 'change', this.render );
// Calls special function for price change
this.listenTo( this.model, 'change:price', this.onPriceChange );
return this.render();
},
render: function() {
// Populate the view's DOM element with the compiled template reflecting the model
this.$el.html( this.template(this.model.attributes) );
return this;
},
onPriceChange: function() {
// Do something special for price change, maybe trigger a global event?
Backbone.trigger('item:price:change', this.model );
}
});
var item = new Item({ id : 1 });
item.fetch();
var itemView = new ItemView({ model : item });
// Insert the view's element inside the DOM
$('#item-placeholder').append( itemView.el );