Javascript 主干视图类事件在创建实例时被覆盖

Javascript 主干视图类事件在创建实例时被覆盖,javascript,events,backbone.js,prototypal-inheritance,Javascript,Events,Backbone.js,Prototypal Inheritance,我创建了一个从主干.View继承的类,该类定义了一些DOM事件: var MyView = Backbone.View.extend({ el: '#myview', events: { 'click .somebutton': 'somefunction', 'click .otherbutton': 'otherfunction' }, somefunction: function(){ console.log('somefunction!'); }, o

我创建了一个从主干.View继承的类,该类定义了一些DOM事件:

var MyView = Backbone.View.extend({
  el: '#myview',
  events: {
    'click .somebutton': 'somefunction',
    'click .otherbutton': 'otherfunction'
  },
  somefunction: function(){ console.log('somefunction!'); },
  otherfunction: function(){ console.log('otherfunction!');  }
});
当实例化此视图时(
newmyview();
),所有视图看起来都是有序的,只要单击元素,就会触发我的回调

但是,如果我像这样实例化我的视图:

new MyView({
  events: {
    'click .thirdbutton': function(){ 
       console.log('thirdfunction'); 
    }
  }
});
new MyView({
  extraEvents: {
    'click .thirdbutton': function(){ 
       console.log('thirdfunction'); 
    }
  }
});

我现有的所有类事件都被这个事件覆盖。将仅实例事件与现有类事件合并的正确方法是什么?在我的示例中,我希望所有3个事件在我的实例中都处于活动状态。

您可以在
初始化
-方法中执行此操作

initialize: function() {
  _.extend(this.events, {
    'click .thirdbutton': function() {...}
  });
}

这可能不是最漂亮的答案,但它应该会起作用。

找到了一个解决方案,多亏了这个答案:

我在类的选项中添加了一个
extraEvents
键,并将
events
对象更改为一个合并额外事件的函数。下面的代码示例,如果对其他人有帮助:

var MyView = Backbone.View.extend({
  el: '#myview',
  options: {
    extraEvents: {}      
  },
  originalEvents: {
    'click .somebutton': 'somefunction',
    'click .otherbutton': 'otherfunction'
  },
  events: function(){
    return _.extend({}, this.originalEvents, this.options.extraEvents);
  },
  somefunction: function(){ console.log('somefunction!'); },
  otherfunction: function(){ console.log('otherfunction!');  }
});
现在我可以像这样实例化我的视图:

new MyView({
  events: {
    'click .thirdbutton': function(){ 
       console.log('thirdfunction'); 
    }
  }
});
new MyView({
  extraEvents: {
    'click .thirdbutton': function(){ 
       console.log('thirdfunction'); 
    }
  }
});

谢谢你的回答!我认为这适用于更简单的情况。关键是,在我的例子中,我需要类上的initialize方法,并且我正在创建该类的多个实例,每个实例都有不同的事件+1.谢谢你的努力。我没有提供足够的信息。(已经解决了我的问题,请看我自己的答案)