Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  42] [ 6]  / answers: 1 / hits: 27727  / 12 Years ago, mon, april 2, 2012, 12:00:00

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.


More From » backbone.js

 Answers
36

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

[#86452] Saturday, March 31, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;