thoughts
Asynchronous method chainer
2009-08-22
Ever encountered having a bunch of methods doing asynchronous things that you would really like to chain? I have written a little chainer utility to do just that. Instead of giving callback parameters to your methods, you can now chain them as if they were synchronous.
Imagine you have some methods that take a callback function to execute when they are done. You end up nesting these. Think about something like:
a.doSomeHTTPRequest(foo,bar,function() {
a.openDialogWindow(some,parameters,function() {
a.acknowledge();
});
});
Or, imagine chained animations:
a.moveRight(200,function() {
a.moveDown(200,function() {
a.moveLeft(200,function() {
a.moveUp(200);
});
});
});
Wouldn't it be nice if you could just do:
a.moveRight(200)
.moveDown(200)
.moveLeft(200)
.moveUp(200);
Let's make that more concrete. Suppose a is an instance of a class Animator with the following signature:
Animator.prototype.moveLeft = function(d,callback)
Animator.prototype.moveRight = function(d,callback,bar)
Animator.prototype.moveUp = function(d,callback)
Animator.prototype.moveDown = function(d,foo,bar,callback)
Note the callback parameter occurs at different locations for illustration.
I can now make a Chainer instance for the Animator instance (a).
var c = new com.rikkertkoppes.util.Chainer(a,{
methods: [
'moveUp','moveDown','moveLeft',
{name:'moveRight', index: 1}
]
});
The constructor takes 2 parameters, the instance to chain and some configuration properties. The methods property is an array listing the methods that you would like to be able to chain. It can be an array of strings or an array of object literals. In the latter case, a name key should at least be present indicating the method name. Optionally, you can indicate which parameter of the method is the callback parameter. By default, the chainer assumes it is the last parameter.
Furthermore, a scope parameter can be added to adjust the scope in which the chain will be executed. By default it is the scope of the instance given.
The chainer is now set up and we are ready to do what we actually wanted to do:
c._chain()
.moveRight(200)
.moveDown(200)
.moveLeft(200)
.moveUp(200)
._do();
Note the _chain and _do methods at the start and end. The latter method indicates that the chain should be executed immediately. Alternatively, one can call the _do method at a later stage. Moreover, one can just omit ._do() and just call the returning chain directly:
c._chain()
.moveRight(200)
.moveDown(200)
.moveLeft(200)
.moveUp(200)();
Get it
All this code is public domain.
- The Javascript class
- Sample HTML (using the YUI animation utility)
Additional resources (top 15)
Below is a list of additional resources that might contain extra information about the subject at hand. These are all sites linking to this one (i.e. backtracking).
