Skip to content

Instantly share code, notes, and snippets.

@FranckErnewein
Created November 27, 2013 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FranckErnewein/7679370 to your computer and use it in GitHub Desktop.
Save FranckErnewein/7679370 to your computer and use it in GitHub Desktop.
jQuery Promise style based on Backbone.Events
define([
'underscore',
'backbone'
], function( _, Backbone ){
function Deferred(){
this.resolved = false;
this.rejected = false;
}
_.extend( Deferred.prototype, Backbone.Events, {
resolve: function( reason ){
if( this.resolved || this.rejected ) return;
this.trigger( 'resolve', reason );
this.resolved = true;
this.reason = reason;
this.off(); //unbind all
},
notice: function( notice ){
},
reject: function( reason ){
if( this.resolved || this.rejected ) return;
this.trigger( 'resolve', reason );
this.trigger( 'reject', reason );
this.rejected = true;
this.reason = reason;
this.off(); //unbind all
},
done: function( func, context ){
if( this.resolved ){
//instant execute
func.call( context || this, this.reason );
}else{
//bind for the future
this.on('resolve', func, context);
}
return this; //allow to chain
},
fail: function( func, context ){
if( this.rejected ){
//instant execute
func.call( context || this, this.reason );
}else{
//bind for the future
this.on('reject', func, context);
}
return this; //allow to chain
}
});
return Deferred;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment