Backbone.js: communication between views

17,578

Solution 1

I wrote up an article a while back on a few different options for coordinating between views: http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/

in your case, i'd recommend using the event aggregator that i describe in that article. you could have each item view listen for a "editmode" event, or something similar. when this event fires, each view that listened for it would update itself to go into edit mode. then you would do the opposite when you click "done" - send a "viewmode" event, or something similar, and have each view update itself appropriately.

Solution 2

My two cents: There is a simple "hack" you can do with backbone.js to actually have a pub/sub that can communicate between views:

Something along these lines (untested):

var EventBus = Backbone.Model.extend({

   publish: function(event, args){

       this.trigger(event, args);

   },

   subscribe: function(event, args) {

       this.bind(event, args);

   }
});

You basically get the idea. Now for every view, have it 'bind' to this EventBus (since views can only bind to models/collections in backbone) - you basically just use the method names publish/subscribe to be in sync with the nomenclature of such a model but you may choose not to. Just create an empty EventBus 'class' in that case and have every view bind to it :)

So every view only needs to be coupled to this EventBus and act on received events! Backbone.js internally handles all the plumbing of this design pattern, so you pretty much get it for free :)

The above code may not run as-is, but is there to give you an idea about it...

Share:
17,578
Sebastian
Author by

Sebastian

Updated on June 05, 2022

Comments

  • Sebastian
    Sebastian about 2 years

    I'm working on a Backbone app that contains a list of entries, much like the example app Todos (http://documentcloud.github.com/backbone/examples/todos/index.html).

    So, I have an App view and one view per list item. Now, say I have a global edit button. The App view would handle a click and what I then want to do is tell each list view to show a delete button.

    In the screenshots below (from Spotify), pressing the Edit button causes all list views to change appearance.

    What's the best way to do this with Backbone. I need to iterate over all list views and call a editMode function. But the App view (out of the box) doesn't know about the list views..

    enter image description here