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.)