是否可以制作一组存在于每个视图中的默认事件?例如,如果我的应用程序中的每个视图都包含一个设置按钮
events: {
"click #settings" : "goSettings"
},
...
goSettings: function() {
// settings show function
});
如何将此事件打包以包含在我的应用程序的每个视图中?
答案 0 :(得分:4)
问题是View#extend
只是覆盖了现有的属性,所以你不能把你的'click #settings'
放在基类和子类中。但是,您可以轻松地将extend
替换为您自己的合并events
的内容。像这样:
var B = Backbone.View.extend({
events: {
'click #settings': 'goSettings'
}
}, {
extend: function(properties, classProperties) {
properties.events = _({}).extend(
properties.events || { },
this.prototype.events
);
return Backbone.View.extend.call(this, properties, classProperties);
}
});
然后为您的观点扩展B
而不是Backbone.View
。
答案 1 :(得分:2)
您可以使用事件和函数创建基本视图,然后从其继承其他视图。我喜欢这里描述的模式,因为它很容易设置并且可以根据需要轻松覆盖:http://www.scottlogic.com/blog/2012/12/14/view-inheritance-in-backbone.html
基本视图如下所示:
var BaseSearchView = function(options) {
this.inheritedEvents = [];
Backbone.View.call(this, options);
}
_.extend(BaseView.prototype, Backbone.View.prototype, {
baseEvents: {},
initialize: function(options) {
// generic initialization here
this.addEvents({
"click #settings" : "goSettings"
});
this.initializeInternal(options);
},
render: function() {
// generic render here
this.renderInternal();
return this;
},
events: function() {
var e = _.extend({}, this.baseEvents);
_.each(this.inheritedEvents, function(events) {
e = _.extend(e, events);
});
return e;
},
addEvents: function(eventObj) {
this.inheritedEvents.push(eventObj);
},
goSettings: function() {
// settings show function
}
});
BaseView.extend = Backbone.View.extend;
你的孩子班这样:
var MyView = BaseView.extend({
initializeInternal: function(options) {
// do something
// add event just for this child
this.addEvents({
"click #differentSettings" : "goSettings"
});
},
renderInternal: function() {
// do something
}
});