backbone.js - how to communicate between views?

Viewed 5883

I have a single page web app with multiple backbone.js views. The views must sometimes communicate with each other. Two examples:

  1. When there are two ways views presenting a collection in different ways simultaneously and a click on an item in one view must be relayed to the other view.
  2. When a user transitions to the next stage of the process and the first view passes data to the second.

To decouple the views as much as possible I currently use custom events to pass the data ($(document).trigger('customEvent', data)). Is there a better way to do this?

3 Answers

jakee's answer suggests a fine approach that I myself have used, but there is another interesting way, and that is to inject a reference to an object into each view instance, with the injected object in turn containing references to as many views as you want to aggregate.

In essence the view-aggregator is a sort of "App" object, and things beside views could be attached, e.g. collections. It does involve extending the view(s) and so might not be to everybody's taste, but on the other hand the extending serves as a simple example for doing so.

I used the code at http://arturadib.com/hello-backbonejs/docs/1.html as the basis for my ListView and then I got the following to work:

define(
    ['./listView'],

    function (ListView) {
        var APP = {
            VIEWS : {}
        }

        ListView.instantiator = ListView.extend({
            initialize : function() {
                this.app = APP;
                ListView.prototype.initialize.apply(this, arguments);
            }
        });

        APP.VIEWS.ListView = new ListView.instantiator();
        console.log(APP.VIEWS.ListView.app);
    }
);
Related