Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created February 7, 2012 15:43
Show Gist options
  • Save mxriverlynn/1760312 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1760312 to your computer and use it in GitHub Desktop.
Backbone.Marionette.Callbaks
// Callbacks
// ---------
// A simple way of managing a collection of callbacks
// and executing them at a later point in time, using jQuery's
// `Deferred` object.
Marionette.Callbacks = function(){
this.deferred = $.Deferred();
this.promise = this.deferred.promise();
};
_.extend(Marionette.Callbacks.prototype, {
// Add a callback to be executed. Callbacks added here are
// guaranteed to execute, even if they are added after the
// `run` method is called.
add: function(callback){
this.promise.done(function(context, options){
callback.call(context, options);
});
},
// Run all registered callbacks with the context specified.
// Additional callbacks can be added after this has been run
// and they will still be executed.
run: function(context, options){
this.deferred.resolve(context, options);
}
});
@yethee
Copy link

yethee commented Feb 7, 2012

In jQuery since 1.7 version has been added Callbacks plugin, which internally used in the Deferred. You can simplify the code, if use jQuery's Callbacks object directly.

I modified your gist, to use the Callbacks instead of the Deferred: https://gist.github.com/1761003

Thank you for your libraries for Backbone!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment