Question

I know the proper way to bind events in Backbone is to use listenTo() rather than on(), as described in this blog post.

initialize: function() {
    this.listenTo(this.model, 'change', this.render);
}

But what if you need to bind events across views?

Up to now, I've been using Backbone's global pubsub:

Backbone.on('custom:event', this.handleEvent);

That works alright, but I've yet to find a clean way to unbind a global event like this. For instance, if the view is replaced by a new instance, I can do this:

Backbone.off('custom:event').on('custom:event', this.handleEvent);

That works as long as nothing else is also listening, but certainly isn't ideal.

I'd prefer to use listenTo(), but don't know how to do this without specifying the view instance that will trigger the event. I suppose I could inject it when the listener is created, but that requires making sure the publisher is already instantiated and seems fragile.

Has anyone come up with a good way to bind events between views?

(In case it matters, the views aren't related -- a.k.a. child view and parent view.)

Was it helpful?

Solution

listenTo is little more than this:

Events.listenTo = function(obj, name, callback) {
  //...
  obj.on(name, callback, this);
  //...
};

Similarly, stopListening is a bunch of bookkeeping wrapped around off. That means that you can listenTo anything that hs the usual on and off methods:

this.listenTo(Backbone, 'custom:event', this.handleEvent, this);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top