Backbone.js的 - 如何在视图之间沟通?
我有多个Backbone.js的意见单个页面的Web应用程序。观点有时必须互相通信。举两个例子:
I have a single page web app with multiple backbone.js views. The views must sometimes communicate with each other. Two examples:
- 在当前有两种方式看待presenting同时以不同的方式收集和在一个视图中的项目的点击必须传达给其他视图。
- 当用户转换到过程的下一阶段,第一视图数据传递到第二
要尽可能我目前使用自定义事件来传递数据脱钩的意见(的$(document).trigger(自定义事件,数据)
)。有没有更好的方式来做到这一点?
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?
一个广泛使用的技术是延长 Backbone.Events
-object创建您的个人全球活动聚合器。
One widely used technique is extending the Backbone.Events
-object to create your personal global events aggregator.
var vent = {}; // or App.vent depending how you want to do this
_.extend(vent, Backbone.Events);
根据如果你使用requirejs或别的东西,你可能想这个分离到它自己的模块,或者使你的应用对象的属性。现在,您可以触发,听你的应用的任何事件。
Depending if you're using requirejs or something else, you might want to separate this into its own module or make it an attribute of your Application object. Now you can trigger and listen to events anywhere in your app.
// View1
vent.trigger('some_event', data1, data2, data3, ...);
// View2
vent.on('some_event', this.reaction_to_some_event);
这也可以让你使用事件聚合模式,集合,路由器等这里是Martin Fowler的理念,为之间的通信事件聚合(在JavaScript)。这里是一个更backboney实施和更Backbone.Marionette的静脉标的反射,但大部分是适用于香草骨干。
This also allows you to use the event aggregator to communicate between models, collections, the router etc. Here is Martin Fowler's concept for the event aggregator (not in javascript). And here is a more backboney implementation and reflection on the subject more in the vein of Backbone.Marionette, but most of it is applicable to vanilla Backbone.
希望这有助于!