我有一个使用视图继承的案例,我的代码看起来基本上像:
parentView = Backbone.View.extend({ events: { "some event": "business" },initialize: function(){ _.bindAll(this); },business: function(e){ ... this.someFunc && this.someFunc(); ... } }); childView = parentView.extend({ events: { ... },constructor: function(){ this.events = _.extend( {},parentView.prototype.events,this.events ); parentView.prototype.initialize.apply( this ); },initialize: function(){ _.bindAll(this); },someFunc: function(){ ... } });
更新:将this.events扩展名移动到构造函数.
我的子视图中有someFunc,在父视图的某些业务功能中,它应该调用该函数(如果存在).如果将其正确设置为childView,则应存在this.someFunc.然而,这不是我遇到的行为.
在初始化函数期间(在父级中),这确实设置为子视图.但是,当某个事件触发时,将调用业务函数,并将此设置为parentView.
解决方法
您是否尝试在构造函数中扩展this.events而不是在initialize函数中?如果你在初始化时这样做,你就太晚了;业务功能的事件委托已经在构造函数中设置,并将指向parentView(请参阅Backbone.View的构造函数中对this.delegateEvents()的调用).
更新了一个工作示例:
ParentView = Backbone.View.extend({ name: 'ParentView',events: { "event": "business" },business: function(e){ this.someFunc && this.someFunc(); } }); ChildView = ParentView.extend({ name: 'ChildView',events: { },ParentView.prototype.events,this.events ); console.debug( this.events ); ParentView.prototype.constructor.apply( this,arguments ); },someFunc: function(){ console.debug('someFunc; this.name=%s',this.name); } }); child = new ChildView(); $( child.el ).trigger('event'); // logs 'this' in 'someFunc'; the name is 'ChildView'.