Backbone.js的 - 如何在视图之间沟通? [英] backbone.js - how to communicate between views?

查看:164
本文介绍了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:


  1. 在当前有两种方式看待presenting同时以不同的方式收集和在一个视图中的项目的点击必须传达给其他视图。

  2. 当用户转换到过程的下一阶段,第一视图数据传递到第二

要尽可能我目前使用自定义事件来传递数据脱钩的意见(的$(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)。这里是一个更<一个href=\"http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-learned/\">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.

希望这有助于!

这篇关于Backbone.js的 - 如何在视图之间沟通?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆