Eventbus/Aggregator for two Requirejs apps

I have two applications (more to be added that may or may not use backbone + requirejs), both developed using backbone + requirejs. I want to create an eventbus on which both applications can publish and subscribe to specific events. I have considered a two options, both of which have their own inefficiencies. These include:

  • Using the document object since this is common to all applications on the page regardless of framework/architecture eg:
  • // Aggregator
    define([], function () {
        var eventAgg = document.getElementsByTagName('body')[0],
            slice = Array.prototype.slice;
    
        function _on() {
            var args = slice.call(arguments);
            eventAgg.addEventListener(arg[0], arg[1]);
        }
    
        function _trigger() {
            var args = slice.call(arguments);
            eventAgg.dispatchEvent(arg[0]);
        }
    
        return {
            on: _on,
            trigger: _trigger
        };
    });
    
    // Somewhere in one of app 1's modules
    define(['jquery', 
            'underscore', 
            'backbone', 
            'dispatch',
            'someView'], function ($, _, Backbone, Dispatch, SomeView) {
    
        ...
        Dispatch.on('init', function (e) {...};);
        ...
    });
    
    // Somewhere in one of app 2's modules
    
    ...
    var customEvent =  new CustomEvent('init', {'status': 'All data loaded successfully'});
    dispatcher.dispatchEvent(event);
    ...
    
  • Extending Backbone.Events and injecting the event aggregator into all requirejs modules (though this approach has been finicky at best). Same approach as above except I extend Backbone.Events instead of using the document object.
  • Neither of these methods seem 'correct' for providing an global event aggregator but I have not been able to come up with anything better. Any suggestions?


    Backbone is itself, an event bus. Which is probably the most straight forward way of doing it.

    Backbone.on('myevent:app1', function(){alert('sup');})
    Backbone.trigger('myevent:app1');
    
    链接地址: http://www.djcxy.com/p/70414.html

    上一篇: 用JSDoc记录一个Backbone构造函数?

    下一篇: Eventbus / Aggregator用于两个Requirejs应用程序