Backbone JS: can one view trigger updates in other views?

mvbl fst picture mvbl fst · Apr 3, 2012 · Viewed 27.3k times · Source

In my simple project I have 2 views - a line item view (Brand) and App. I have attached function that allows selecting multiple items:

var BrandView = Backbone.View.extend({
...some code...
    toggle_select: function() {
        this.model.selected = !this.model.selected;
        if(this.model.selected) $(this.el).addClass('selected');
        else $(this.el).removeClass('selected');
        return this;
    }
});

var AppView = Backbone.View.extend({
...some code...
    delete_selected: function() {
        _.each(Brands.selected(), function(model){ 
            model.delete_selected();
        });
        return false;
    },
});

Thing is, I want to know how many items are selected. In this setup selecting is NOT affecting the model and thus not firing any events. And from MVC concept I understand that views should not be directly talking to other views. So how can AppView know that something is being selected in BrandViews?

And more specifically, I AppView to know how many items were selected, so if more than 1 is selected, I show a menu for multiple selection.

Answer

stusmith picture stusmith · Apr 3, 2012

You might want to have a read of this discussion of Backbone pub/sub events:

http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/

I like to add it in as a global event mechanism:

Backbone.pubSub = _.extend({}, Backbone.Events);

Then in one view you can trigger an event:

Backbone.pubSub.trigger('my-event', payload);

And in another you can listen:

Backbone.pubSub.on('my-event', this.onMyEvent, this);