主干视图:从父级继承和扩展事件

Backbone View: Inherit and extend events from parent

本文关键字:继承 扩展 事件 视图      更新时间:2023-09-26

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'
      });
   }
});

soldier.moth的答案很好。进一步简化它,您可以执行以下操作

var ChildView = ParentView.extend({
   initialize: function(){
       _.extend(this.events, ParentView.prototype.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,要么是继承的类。

访问任何咖啡脚本Class … extends …中可用的_super变量

// ModalView.js
var ModalView = Backbone.View.extend({
	events: {
		'click .close-button': 'closeButtonClicked'
	},
	closeButtonClicked: function() { /* Whatever */ }
	// Other stuff that the modal does
});
ModalView.extend = function(child) {
	var view = Backbone.View.extend.apply(this, arguments);
	view.prototype.events = _.extend({}, this.prototype.events, child.events);
	return view;
};
// MessageModalView.js
var MessageModalView = ModalView.extend({
	events: {
		'click .share': 'shareButtonClicked'
	},
	shareButtonClicked: function() { /* Whatever */ }
});
// ChatModalView.js
var ChatModalView = ModalView.extend({
	events: {
		'click .send-button': 'sendButtonClicked'
	},
	sendButtonClicked: function() { /* Whatever */ }
});

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",
}

我在本文中找到了更有趣的解决方案

它使用了 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来进一步简化 soldier.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'
        });
    }
});

我更喜欢这种方法,因为您不必识别父变量 - 少一个要更改的变量。我对attributesdefaults使用相同的逻辑.

哇,

这里有很多答案,但我想我会再提供一个。 如果您使用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