Evan Emolo
Evan Emolo

Reputation: 1670

Backbonejs: Listening for button clicks on seperate view

I have a parent view (View.A) that manages child views View.B and View.C. View.B has a button interface that controls events on View.B.

setup

View.A
  View.B
    view.B.template.html
  View.C
    view.C.template.html

View.B.template.html

<div class="btn-group">
  <button id="button-1" type="button" class="btn btn-default">
    Button 1
  </button>
  <button id="button-2" type="button" class="btn btn-default">
    Button 2
  </button>
</div>

View.B view

var View.B = Backbone.View.extend({
  template: _.template( view.B.template.html ),
  events: {
    'click #button-1': 'someMethod',
    'click #button-2': 'anotherMethod'
  },
  ...
})

What I would like to do is control events on View.C as well with the View.B buttons. I have attempted to add delegatedEvents to View.C that listen for clicks on the buttons ids in the View.B template, but that does not work. Is there a work-around for this?

Upvotes: 3

Views: 286

Answers (1)

kalley
kalley

Reputation: 18462

I would create an eventaggregator, something like:

var vent = _.extend({}, Backbone.Events);

Then you can listen and trigger events on that. So you'd have something like this:

// This would be from View.B
someMethod: function(ev) {
    vent.trigger('someMethod', ev);
}

// And this would be in View.C
initialize: function() {
    this.listenTo(vent, 'someMethod', this.mySomeMethod);
}

Then you can reuse the event aggregator where necessary. MarionetteJS does this.

Upvotes: 3

Related Questions