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:
// 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);
...
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
