简体   繁体   English

在Backbone.js视图之间传递消息

[英]Pass Messages Between Backbone.js Views

I'm currently working on a bug in my company's backbone application in which a task in progress in one view should disable behavior in another view. 我目前正在研究公司骨干应用程序中的错误,该错误中一个视图中正在进行的任务应禁用另一视图中的行为。 The behavior we're looking for is when the task begins and the user navigates to the second view, the behavior is already disabled, but because the view hasn't been rendered yet the event to disable the behavior isn't triggering. 我们正在寻找的行为是当任务开始并且用户导航到第二个视图时,该行为已经被禁用,但是由于尚未呈现该视图,因此不会触发禁用行为的事件。

Is there a way around this without parameterizing the view? 是否可以解决此问题而不对视图进行参数化?

Current code is as follows: 当前代码如下:

In settings.js: 在settings.js中:

handleUpdateClick: function(evt) {
    // ...
    EventDispatcher.trigger('updatingStateChanged');
    // ...
}

In dashboard.js: 在dashboard.js中:

initialize: function(options) {
    EventDispatcher.on("updatingStateChanged", this.handleUpdatingStateChanged);
    // ...
}

通常,许多应用程序要做的是具有全局“应用程序状态”模型,您可以在其中存储当前状态,并可以在组件之间共享数据/事件。

另一个选择是拥有一个可能基于Backbone.Router的全局应用程序控制器,该控制器充当事件和消息传递的单例-在大型项目中经常看到这种情况。

To add to the current answers, in one of my Backbone apps I created a central Hub to listen for events. 为了增加当前的答案,在我的一个Backbone应用程序中,我创建了一个中央集线器来监听事件。 So it works like this 所以它像这样

//This is outside your view code
var HUB = {};
_.extend(HUB, Backbone.Events);

In your view you listen for events on the Hub: 在您看来,您会在Hub上监听事件:

initialize: function(options) {
    HUB.on('state:change', this.handleUpdatingStateChanged, this);        
        // ...
}

Then in your settings.js you can trigger events against the Hub like so: 然后在您的settings.js中,您可以像这样触发针对Hub的事件:

handleUpdateClick: function(evt) {
    // ...
    HUB.trigger('state:change');
    // ...
}

I think this approach could solve your problem. 我认为这种方法可以解决您的问题。 It's quite simple to implement too. 实现起来也很简单。 One important gotcha is that you must remember to stop listening and undelegate events from the hub when you close a view - typically you'd just add a HUB.off(null, null, this); 一个重要的陷阱是,关闭视图时,您必须记住停止从集线器监听和取消删除事件-通常,您只需添加HUB.off(null, null, this); to your existing zombie view cleanup/close approach. 您现有的僵尸视图清理/关闭方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM