Created
June 26, 2009 14:23
-
-
Save agoragames/136525 to your computer and use it in GitHub Desktop.
Callback chains with continuations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// callbacks.js should be included before everything else so any file can add callbacks (before the actual triggers for those callbacks are defined) | |
var Callbacks = { | |
// Define the default callback containers | |
Hydra : { | |
before_fire : [], | |
after_fire : [], | |
on_error : [], | |
on_load : [] | |
}, | |
// namespace our Continuation glue | |
Continuations : { | |
link : function (func, continuation, parameters) { | |
return function () { | |
// only break the continuation chain if the method explicitly returns false | |
if(false !== func.apply(null, parameters)) { | |
continuation () | |
return true | |
} | |
else { return false } | |
} | |
}, | |
chain : function (funcs, parameters) { | |
var cc = Callbacks.Continuations.pass | |
for (var idx = funcs.length - 1; idx >= 0; --idx) | |
cc = Callbacks.Continuations.link(funcs[idx], cc, parameters) | |
return cc | |
}, | |
pass : function () { } | |
}, | |
/* loc is the array to store the callback on (usually something like | |
* Callbacks.Hydra.on_load). | |
* Use with something like: | |
* | |
* Callbacks.add(Callbacks.Hydra.on_load, function() { alert('f1') }) | |
* Callbacks.add(Callbacks.Hydra.on_load, function() { alert('f2') }) | |
* | |
* and then instantiate from the body-onload event (for example) with: | |
* | |
* <body onload="Callbacks.start(Callbacks.Hydra.on_load)"> | |
*/ | |
add : function(loc, callback_function) { | |
loc.push(callback_function) | |
}, | |
// return the success of our chain so the calling method can actually do something with it | |
start : function(loc, parameters) { | |
return Callbacks.Continuations.chain(loc, parameters)() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment