117

Backbone 的文档指出:

events 属性也可以定义为返回事件哈希的函数,以便更容易以编程方式定义事件,以及从父视图继承它们。

你如何继承父母的视图事件并扩展它们?

父视图

var ParentView = Backbone.View.extend({
   events: {
      'click': 'onclick'
   }
});

子视图

var ChildView = ParentView.extend({
   events: function(){
      ????
   }
});
4

15 回答 15

192

一种方法是:

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'
      });
   }
});
于 2012-02-22T21:56:00.137 回答
79

士兵蛾的答案是一个很好的答案。进一步简化它,您可以执行以下操作

var ChildView = ParentView.extend({
   initialize: function(){
       _.extend(this.events, ParentView.prototype.events);
   }
});

然后只需以典型方式在任一类中定义您的事件。

于 2012-04-05T09:07:40.627 回答
12

您还可以使用该defaults方法来避免创建空对象{}

var ChildView = ParentView.extend({
  events: function(){
    return _.defaults({
      'click' : 'onclickChild'
    }, ParentView.prototype.events);
  }
});
于 2012-10-27T16:44:27.830 回答
10

如果您使用 CoffeeScript 并将函数设置为events,则可以使用super.

class ParentView extends Backbone.View
  events: ->
    'foo' : 'doSomething'

class ChildView extends ParentView
  events: ->
    _.extend {}, super,
      'bar' : 'doOtherThing'
于 2013-08-23T10:09:53.607 回答
6

从 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 或其派生类之一扩展来实现。

我们避免了在子视图中以编程方式定义事件函数的需要,在大多数情况下,子视图需要显式引用父构造函数。

于 2015-05-26T11:49:11.473 回答
2

@soldier.moth 最后建议的简短版本:

var ChildView = ParentView.extend({
  events: function(){
    return _.extend({}, _.result(ParentView.prototype, 'events') || {}, {
      'click' : 'onclickChild'
    });
  }
});
于 2013-08-22T12:38:16.763 回答
2

// 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/

于 2015-04-21T03:05:49.733 回答
2
于 2014-08-17T00:50:11.320 回答
1

对于 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",
    }
    // ...
});

...其中 - in A_View.js- 将导致:

events: {
    "click .a_foo": "a_bar",
    "click .b_foo": "b_bar",
    "click .c_foo": "c_bar",
}
于 2016-01-12T16:03:33.510 回答
1

我在这篇文章中找到了一个更有趣的解决方案

它使用了 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);
    },
    ...
});

您也可以对uiattributes执行此操作。

这个例子没有处理函数设置的属性,但是文章的作者在这种情况下提供了一个解决方案。

于 2016-10-21T16:41:47.953 回答
1

要完全在父类中执行此操作并在子类中支持基于函数的事件哈希,以便子类可以与继承无关(MyView.prototype.initialize如果覆盖,子类将不得不调用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);
    };
  }
});
于 2017-06-20T17:36:05.587 回答
0

如果您确定ParentView将事件定义为对象并且您不需要在其中动态定义事件,ChildView则可以通过摆脱函数并_.extend直接使用来进一步简化士兵的回答:

var ParentView = Backbone.View.extend({
    events: {
        'click': 'onclick'
    }
});

var ChildView = ParentView.extend({
    events: _.extend({}, ParentView.prototype.events, {
        'click' : 'onclickChild'
    })
});
于 2015-01-30T17:29:19.247 回答
0

这个 CoffeeScript 解决方案对我有用(并考虑了@soldier.moth 的建议):

class ParentView extends Backbone.View
  events: ->
    'foo' : 'doSomething'

class ChildView extends ParentView
  events: ->
    _.extend({}, _.result(ParentView.prototype, 'events') || {},
      'bar' : 'doOtherThing')
于 2013-10-14T21:53:52.490 回答
0

我喜欢的一个模式是修改构造函数并添加一些额外的功能:

// 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

于 2015-03-26T19:37:35.087 回答
0

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

于 2015-10-04T03:43:56.630 回答