Backbone 的文档指出:
events 属性也可以定义为返回事件哈希的函数,以便更容易以编程方式定义事件,以及从父视图继承它们。
你如何继承父母的视图事件并扩展它们?
父视图
var ParentView = Backbone.View.extend({
events: {
'click': 'onclick'
}
});
子视图
var ChildView = ParentView.extend({
events: function(){
????
}
});
一种方法是:
var ChildView = ParentView.extend({
events: function(){
return _.extend({},ParentView.prototype.events,{
'click' : 'onclickChild'
});
}
});
另一个是:
var ParentView = Backbone.View.extend({
originalEvents: {
'click': 'onclick'
},
//Override this event hash in
//a child view
additionalEvents: {
},
events : function() {
return _.extend({},this.originalEvents,this.additionalEvents);
}
});
var ChildView = ParentView.extend({
additionalEvents: {
'click' : ' onclickChild'
}
});
检查事件是函数还是对象
var ChildView = ParentView.extend({
events: function(){
var parentEvents = ParentView.prototype.events;
if(_.isFunction(parentEvents)){
parentEvents = parentEvents();
}
return _.extend({},parentEvents,{
'click' : 'onclickChild'
});
}
});
士兵蛾的答案是一个很好的答案。进一步简化它,您可以执行以下操作
var ChildView = ParentView.extend({
initialize: function(){
_.extend(this.events, ParentView.prototype.events);
}
});
然后只需以典型方式在任一类中定义您的事件。
this.events
& ParentView.prototype.events
否则,如果两者都在同一事件上定义处理程序,则父处理程序将覆盖子处理程序。
{},ParentView.prototype.events,this.events
delegateEvents
来绑定事件。那么当您在 initialize
中扩展它时,为什么还不算太晚?
initialize
(然后还必须处理管理该函数的层次结构) 只是为了合并事件对象。对我来说,保持 events
合并似乎更干净。话虽如此,我不会想到这种方法,而且被迫以不同的方式看待事物总是很好的 :)
您还可以使用 defaults
方法来避免创建空对象 {}
。
var ChildView = ParentView.extend({
events: function(){
return _.defaults({
'click' : 'onclickChild'
}, ParentView.prototype.events);
}
});
如果您使用 CoffeeScript 并将函数设置为 events
,则可以使用 super
。
class ParentView extends Backbone.View
events: ->
'foo' : 'doSomething'
class ChildView extends ParentView
events: ->
_.extend {}, super,
'bar' : 'doOtherThing'
从 Backbone.View 创建专门的基础构造函数来处理层次结构上的事件继承不是更容易吗?
BaseView = Backbone.View.extend {
# your prototype defaults
},
{
# redefine the 'extend' function as decorated function of Backbone.View
extend: (protoProps, staticProps) ->
parent = this
# we have access to the parent constructor as 'this' so we don't need
# to mess around with the instance context when dealing with solutions
# where the constructor has already been created - we won't need to
# make calls with the likes of the following:
# this.constructor.__super__.events
inheritedEvents = _.extend {},
(parent.prototype.events ?= {}),
(protoProps.events ?= {})
protoProps.events = inheritedEvents
view = Backbone.View.extend.apply parent, arguments
return view
}
这允许我们在使用重新定义的扩展函数创建新的“子类”(子构造函数)时减少(合并)事件散列到层次结构中。
# AppView is a child constructor created by the redefined extend function
# found in BaseView.extend.
AppView = BaseView.extend {
events: {
'click #app-main': 'clickAppMain'
}
}
# SectionView, in turn inherits from AppView, and will have a reduced/merged
# events hash. AppView.prototype.events = {'click #app-main': ...., 'click #section-main': ... }
SectionView = AppView.extend {
events: {
'click #section-main': 'clickSectionMain'
}
}
# instantiated views still keep the prototype chain, nothing has changed
# sectionView instanceof SectionView => true
# sectionView instanceof AppView => true
# sectionView instanceof BaseView => true
# sectionView instanceof Backbone.View => also true, redefining 'extend' does not break the prototype chain.
sectionView = new SectionView {
el: ....
model: ....
}
通过创建一个专门的视图:重新定义扩展功能的 BaseView,我们可以让想要继承其父视图声明的事件的子视图(如 AppView、SectionView)只需通过从 BaseView 或其派生之一扩展来实现。
我们避免了在子视图中以编程方式定义事件函数的需要,在大多数情况下,子视图需要显式引用父构造函数。
@soldier.moth 最后建议的简短版本:
var ChildView = ParentView.extend({
events: function(){
return _.extend({}, _.result(ParentView.prototype, 'events') || {}, {
'click' : 'onclickChild'
});
}
});
这也可以:
class ParentView extends Backbone.View
events: ->
'foo' : 'doSomething'
class ChildView extends ParentView
events: ->
_.extend({}, _.result(_super::, 'events') || {},
'bar' : 'doOtherThing')
直接使用 super
对我不起作用,要么是手动指定 ParentView
要么是继承的类。
访问任何咖啡脚本中可用的 _super
var Class … extends …
// ModalView.js var ModalView = Backbone.View.extend({ events: { 'click .close-button': 'closeButtonClicked' }, closeButtonClicked: function() { /* 不管 */ } // 模态的其他东西做 }); ModalView.extend = function(child) { var view = Backbone.View.extend.apply(this, arguments); view.prototype.events = _.extend({}, this.prototype.events, child.events);返回视图; }; // MessageModalView.js var MessageModalView = ModalView.extend({ events: { 'click .share': 'shareButtonClicked' }, shareButtonClicked: function() { /* 不管 */ } }); // ChatModalView.js var ChatModalView = ModalView.extend({ events: { 'click .send-button': 'sendButtonClicked' }, sendButtonClicked: function() { /* 不管 */ } });
http://danhough.com/blog/backbone-view-inheritance/
对于 Backbone 版本 1.2.3,__super__
工作正常,甚至可能被链接。例如:
// A_View.js
var a_view = B_View.extend({
// ...
events: function(){
return _.extend({}, a_view.__super__.events.call(this), { // Function - call it
"click .a_foo": "a_bar",
});
}
// ...
});
// B_View.js
var b_view = C_View.extend({
// ...
events: function(){
return _.extend({}, b_view.__super__.events, { // Object refence
"click .b_foo": "b_bar",
});
}
// ...
});
// C_View.js
var c_view = Backbone.View.extend({
// ...
events: {
"click .c_foo": "c_bar",
}
// ...
});
...其中 - 在 A_View.js
中 - 将导致:
events: {
"click .a_foo": "a_bar",
"click .b_foo": "b_bar",
"click .c_foo": "c_bar",
}
我在这个article中找到了更有趣的解决方案
它使用了 Backbone 的 super 和 ECMAScript 的 hasOwnProperty。它的第二个进步的例子就像一个魅力。这是一个代码:
var ModalView = Backbone.View.extend({
constructor: function() {
var prototype = this.constructor.prototype;
this.events = {};
this.defaultOptions = {};
this.className = "";
while (prototype) {
if (prototype.hasOwnProperty("events")) {
_.defaults(this.events, prototype.events);
}
if (prototype.hasOwnProperty("defaultOptions")) {
_.defaults(this.defaultOptions, prototype.defaultOptions);
}
if (prototype.hasOwnProperty("className")) {
this.className += " " + prototype.className;
}
prototype = prototype.constructor.__super__;
}
Backbone.View.apply(this, arguments);
},
...
});
您也可以对 ui 和属性执行此操作。
这个例子没有处理函数设置的属性,但是文章的作者在这种情况下提供了一个解决方案。
要完全在父类中执行此操作并在子类中支持基于函数的事件哈希,以便子类可以与继承无关(如果子类覆盖 initialize
,则子类将不得不调用 MyView.prototype.initialize
):
var MyView = Backbone.View.extend({
events: { /* ... */ },
initialize: function(settings)
{
var origChildEvents = this.events;
this.events = function() {
var childEvents = origChildEvents;
if(_.isFunction(childEvents))
childEvents = childEvents.call(this);
return _.extend({}, MyView.prototype.events, childEvents);
};
}
});
这个 CoffeeScript 解决方案对我有用(并考虑了@soldier.moth 的建议):
class ParentView extends Backbone.View
events: ->
'foo' : 'doSomething'
class ChildView extends ParentView
events: ->
_.extend({}, _.result(ParentView.prototype, 'events') || {},
'bar' : 'doOtherThing')
如果您确定 ParentView
将事件定义为对象,并且您不需要在 ChildView
中动态定义事件,则可以通过摆脱该函数并使用 _.extend
来进一步简化战士.moth 的答案直接地:
var ParentView = Backbone.View.extend({
events: {
'click': 'onclick'
}
});
var ChildView = ParentView.extend({
events: _.extend({}, ParentView.prototype.events, {
'click' : 'onclickChild'
})
});
我喜欢的一个模式是修改构造函数并添加一些额外的功能:
// App View
var AppView = Backbone.View.extend({
constructor: function(){
this.events = _.result(this, 'events', {});
Backbone.View.apply(this, arguments);
},
_superEvents: function(events){
var sooper = _.result(this.constructor.__super__, 'events', {});
return _.extend({}, sooper, events);
}
});
// Parent View
var ParentView = AppView.extend({
events: {
'click': 'onclick'
}
});
// Child View
var ChildView = ParentView.extend({
events: function(){
return this._superEvents({
'click' : 'onclickChild'
});
}
});
我更喜欢这种方法,因为您不必识别父级 - 少一个变量来更改。我对 attributes
和 defaults
使用相同的逻辑。
哇,这里有很多答案,但我想我会再提供一个。如果您使用 BackSupport 库,它会提供 extend2
。如果您使用 extend2
,它会自动为您合并 events
(以及 defaults
和类似属性)。
这是一个简单的例子:
var Parent = BackSupport.View.extend({
events: {
change: '_handleChange'
}
});
var Child = parent.extend2({
events: {
click: '_handleClick'
}
});
Child.prototype.events.change // exists
Child.prototype.events.click // exists
https://github.com/machineghost/BackSupport
extend2
) 是我能想到的最好的版本,而且我不认为它有那么糟糕:任何使用 Backbone 的人都已经习惯使用 extend
,所以这样他们就不需要记住一个新的命令。
不定期副业成功案例分享
parentEvents = _.result(ParentView.prototype, 'events');
而不是“手动”检查events
是否是一个函数。_.result
。对于任何感兴趣的人,这里有一个 jsfiddle,其中包含许多关于这个主题的变体:jsfiddlethis
而不是必须按实例名称调用父类。非常感谢你。