0

I have a custom event triggered upon user interaction on a bbone view of a collection, and I'd like that to signal changes on another unrelated view. For this I use a custom event.

//a global event object for my pub-sub model
var vent = Backbone.extend({}, Backbone.Event);

var C1 = Backbone.Collection.extend();
var V1 = Backbone.View.extend(
  events: {
    'click .appointment': 'clickCallback'
  },

  clickCallback: function(){
    vent.trigger('appointment:selected', apptProps);
  }
);

var c1Obj = new C1([{...}, {...}]);
var v1Obj = new V1({
  collection: c1Obj
});

So when user clicks on a .appointment element of the collection view v1Obj, this will announce an appointment:selected event.

Now I want a different view V2 to react to this event. Where would be the best place to bind to the "appointment:selected" event? In the initialize() of view V2 (CASE 1) or in the initialize() of the collection/model of the V2 (CASE 2) or somewhere else? I'm trying to clarify what's the best practice, if any.

CASE 1:

var V2 = Backbone.View.extend(
  initialize: function(){
    vent.on('appointment:selected', this.apptSelected, this);
  },
  appSelected: function(apptProps){
    ...
  }
);

CASE 2:

var C2 = Backbone.Collection.extend(
  initialize: function(){
    vent.on('appointment:selected', this.apptSelected, this);
  },
  appSelected: function(apptProps){
    ...
  }
);

As far as I understand, the philosophy of Bbone upon user interaction, is to manipulate the data and not modify the markup, the idea being that data changes cascade to the views. If so, the answer to the original question is CASE 2?

Thalis K.
  • 7,363
  • 6
  • 39
  • 54
  • You could consider something like [this](http://stackoverflow.com/a/10471303/834178). Then your views can listen for model change events, like `this.listenTo([model/collection], 'change:selected', this.apptSelected)`. – Paul Hoenecke Feb 15 '13 at 15:55

1 Answers1

1

I would think the most idiomatic thing would be:

  • represent the state of "selected" by inclusion in a collection
  • When the user clicks .appointment, view1 adds the appointment model to the selectedAppointments collection
  • view2 binds to the normal collection lifecycle events (add, remove, reset) of selectedAppointments and re-renders itself accordingly
  • Both views take this collection in their options argument to initialize

Just a side note that as of Backbone 0.9.9 the Backbone object itself can be used as an application-wide event bus instead of your vent object.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274