简体   繁体   English

backbone.js +全局事件调度程序+ require.js:操作方法?

[英]backbone.js + global event dispatcher + require.js: how-to?

I have a number of backbone models, organized in collections and connected to their corresponding views and/or collections of views. 我有许多骨干模型,按集合进行组织并连接到相应的视图和/或视图集合。 Some of these models that do not belong to the same collection need to trigger an event which is of interest to another model (and maybe more than one). 其中一些不属于同一集合的模型需要触发另一个模型(可能不止一个)感兴趣的事件。

The recommended way to deal with this is, I think, the "global event dispatcher/aggregator" as described here and other places. 我认为,推荐的处理方法是这里和其他地方所描述的“全球事件调度员/聚合器”。

However, I also happen to be using require.js, which seems to go against the idea of attaching the dispatcher/aggregator to the application's namespace object -- or am I wrong here? 但是,我也碰巧使用require.js,这似乎违背了将调度程序/聚合器附加到应用程序的命名空间对象的想法 - 或者我错在这里?

So my question is: using require.js how can I have a number of different backbone models trigger an event that will be handled by another model? 所以我的问题是:使用require.js我怎样才能有一些不同的骨干模型触发一个将由另一个模型处理的事件?

A similar solution to what @Andreas proposed but without Backbone.Marionette (heavily inspired nonetheless, see the article linked in the question ). 类似于@Andreas提出但没有Backbone.Marionette的解决方案(尽管如此, 请参阅问题中链接的文章 )。

All you have to do is to define a module that creates a singleton of an event listener and require this object in the modules where you want to trigger an event or listen to this event. 您所要做的就是定义一个模块,该模块创建一个事件监听器的单例,并在要触发事件或监听此事件的模块中需要此对象。

Let's say you have app/channel.js defining your channel 假设您有定义频道的app / channel.js

define(['backbone', 'underscore'], function (Backbone, _) {
    var channel = _.extend({}, Backbone.Events); 
    return channel;
});

You can then use it as a listener via 然后,您可以将其用作侦听器

require(['app/channel'], function (channel) {
    channel.on('app.event', function () {
        console.log('app.event');
    });
});

and you can trigger an event on this channel via 你可以通过这个频道触发一个事件

require(['app/channel'], function (channel) {
    channel.trigger('app.event');
});

We using Marionettes app.vent (which is the global event transmitter for our application), allong with require js and it works really well. 我们使用Marionettes app.vent (它是我们应用程序的全局事件发送器),allong with require js,它运行得非常好。

app 应用

define(, function(){
  return new Backbone.Marionette.Application();
})

Model1 型号1

define(['app'], function(app){
  return Backbone.Marionette.Model.extend({
    initialize: function(){
      this.bindTo('app.vent', 'create:model2', this.toSomething, this);
    }
  })
})

Model2 MODEL2

define(['app'], function(app){
  return Backbone.Marionette.Model.extend({
    initialize: function(){
      app.vent.trigger('create:model2', this);
    }
  })
})

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

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