问题描述
在我简单的项目,我有2次 - 行项目视图(品牌)和应用程序。我重视功能,可以选择多个项目:
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;
},
});
事情是,我想知道有多少项被选中。在这种设置中选择不影响模型,因此不会触发任何事件。而从MVC的概念我理解的观点不应该被直接对话的视图。那么,怎样才能APPVIEW知道什么是BrandViews被选中?
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?
更确切地说,我APPVIEW知道有多少项被选中,所以如果选择大于1,我显示了多重选择的菜单。
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.
推荐答案
您可能希望有骨干的pub / sub事件本次讨论的读:
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);
和在另一个你可以听:
Backbone.pubSub.on('my-event', this.onMyEvent, this);
这篇关于骨干JS:在其他意见,可以一个视图触发更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!