骨干视图Backbone.Events
混合在一起,因此视图可以产生自己的事件,而其他视图可以监听这些事件。因此,您AvatarView
可以在选择事件时触发事件:
select: function() {
// Mark this avatar as selected...
this.trigger('selected', this);
},
unselect: function() {
// Undo the "mark this avatar as selected" from above.
}
然后AvatarAppView
可以监听这些事件:
initialize: function() {
_.bindAll(this, 'selected');
//...
},
render: function() {
this.kids = [ ];
this.collection.each(function(m) {
var v = new AvatarView({ model: m });
v.on('selected', this.selected);
this.kids.push(v);
this.$el.append(v.render().el);
}, this);
return this;
}
然后是一个简单的selected
事件处理程序,AvatarAppView
用于取消选择其他AvatarView
s:
selected: function(v) {
_.chain(this.kids).reject(function(k) { return k == v }).invoke('unselect');
}
演示:http: //jsfiddle.net/ambiguous/thRHK/