Skip to content

Instantly share code, notes, and snippets.

@cobbweb
Created November 23, 2012 03:26
Show Gist options
  • Save cobbweb/4133877 to your computer and use it in GitHub Desktop.
Save cobbweb/4133877 to your computer and use it in GitHub Desktop.
Queued Triggers in Backbone.Events
App.module('ModuleOne', function(ModuleOne, App) {
var members = new Backbone.Collection();
members.on('reset', function() {
App.vent.queueTrigger('moduleone:members:reset', members);
});
members.fetch();
});
App.module('ModuleTwo', function(ModuleTwo) {
ModuleTwo.MyView = Marionette.CompositeView.extend({
initialize: function() {
App.vent.on('moduleone:members:reset', this.updateMemberList, this);
},
updateMemberList: function(members)
{
this.collection = members;
this.render();
}
});
});
(function(Events) {
'use strict';
var eventSplitter = /\s+/, on = Events.on;
Events.queueTrigger = function(events) {
Events.trigger.apply(this, arguments);
events = events.split(eventSplitter);
var args = _.rest(arguments), event;
if (!this._queuedTriggers) {
this._queuedTriggers = {};
}
while (event = events.shift()) {
var qt = this._queuedTriggers[event] || (this._queuedTriggers[event] = []);
qt.push(args);
}
return this;
};
Events.on = function(events, callback, context) {
// call original Backbone.Event.on
on.apply(this, arguments);
if (!this._queuedTriggers) {
return;
}
events = events.split(eventSplitter);
var event, qt = this._queuedTriggers;
var run = function(args) {
callback.apply(context, args);
};
while (event = events.shift()) {
if (!qt[event]) {
continue;
}
_.each(qt[event], run);
}
};
}(Backbone.Events));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment