Question

I have created a class inherited from Backbone.View which defines some DOM events:

var MyView = Backbone.View.extend({
  el: '#myview',
  events: {
    'click .somebutton': 'somefunction',
    'click .otherbutton': 'otherfunction'
  },
  somefunction: function(){ console.log('somefunction!'); },
  otherfunction: function(){ console.log('otherfunction!');  }
});

When instantiating this view (new MyView();) all seem to be in order and my callbacks are fired whenever the elements are clicked.

However if I instantiate my view like this:

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

All my existing class events get overriden by this single one. What is the correct way to merge my instance-only events with the existing class events? In my example I want all 3 events to be active in my instance.

Was it helpful?

Solution 2

Found a solution, thanks to this answer: Backbone View: Inherit and extend events from parent

I added a extraEvents key to the options of the class, and I changed my events object to a function that merges the extra events. Code example below, if it helps anyone else:

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

Now I can instantiate my view like this:

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

OTHER TIPS

You could do it in the initialize -method

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

This might not be the prettiest of answers, but it should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top