Skip to content

Instantly share code, notes, and snippets.

@arextar
Created July 18, 2011 14:40
Show Gist options
  • Save arextar/1089702 to your computer and use it in GitHub Desktop.
Save arextar/1089702 to your computer and use it in GitHub Desktop.
Deferred Object
D=(function(){
function trigger(arr,con,args){
for(var x=0;x<arr.length;x++) arr[x].apply(con||null,args||[]);
}
function d(fn){
var w=[],
f=[],
won=0,
failed=0,
con,
args,
x,
ret={
w:w,
f:f,
win:function(){
if(won){
trigger(arguments,con,args)
}
else
{
for(var x=0,a=arguments;x<a.length;x++) w.push(a[x])
}
return ret;
},
fail:function(){
if(failed){
trigger(arguments,con,args)
}
else
{
for(var x=0,a=arguments;x<a.length;x++) f.push(a[x])
}
return ret;
},
wins:function(){
if(won||failed) return ret;
won=1;
trigger(w,con=this,args=arguments);
return ret;
},
fails:function(){
if(won||failed) return ret;
failed=1;
trigger(f,con=this,args=arguments)
return ret;
}
}
fn&&ret.win(fn)
for(x in d.fn) ret[x]=d.fn[x];
return ret;
}
d.fn={};
return d;
})();
D=function(){function b(c){var e=[],f=[],g=0,h=0,i,j,k,l={w:e,f:f,win:function(){if(g)a(arguments,i,j);else for(var b=0,c=arguments;b<c.length;b++)e.push(c[b]);return l},fail:function(){if(h)a(arguments,i,j);else for(var b=0,c=arguments;b<c.length;b++)f.push(c[b]);return l},wins:function(){if(g||h)return l;g=1,a(e,i=this,j=arguments);return l},fails:function(){if(g||h)return l;h=1,a(f,i=this,j=arguments);return l}};c&&l.win(c);for(k in b.fn)l[k]=b.fn[k];return l}function a(a,b,c){for(var d=0;d<a.length;d++)a[d].apply(b||null,c||[])}b.fn={};return b}()
  • D([win:Function])

    • win-Optional function to bind to .win()
  • deferred.win(handlers…)

    • handlers-handlers to bind to success
  • deferred.fail(handlers…)

    • handlers-handlers to bind to failure
  • deferred.wins(arguments…)

    • arguments-Arguments to pass to handlers(uses context of this function in calling handlers)
  • deferred.fails(arguments…)

    • arguments-Arguments to pass to handlers(uses context of this function in calling handlers)
//Declare a deferred object
var def=D();
//Bind a handler to a deferred object
def.win(function(a){
alert(this+" "+a+"!")
})
.fail(function(){
alert("Whoops! something went wrong!")
})
//Trigger a deferred object
def.wins.call("Hello"/*Use .call to set a context*/,"World")
//Bind after the deferred has been triggered(Calls with the same context and arguments that it was triggered with)
def.win(function(a){
alert(a+" "+this+"!")
})
//Attempting to trigger after the deferred object has already been completed will fail
def.fails()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment