yikulju

front-end development

Chaining in AS3

Oct 19th 2008
No Comments
respond
trackback

Recently, I’ve been working on the ZuiPrezi client side backend and there are loads of asynchronous requests for resources, which are, to be precise, a pain in the arse.

For instance, if I need “Arial” and then “Verdana” and then a presentation in this order, I would write something like this:

1
2
3
4
5
6
7
8
backend.getFont("arial", function(data:Font):void
{
 
	backend.getFont("verdana", function(data:Font):void
	{
		backend.loadPresentation(12)
	})
})
It works well, but not only does it look complicated, it could be hard to maintain as well.

Pseudo solution

The way I would describe it in pseudocode could be like this:

1
2
3
4
5
getFont("arial")
then
getFont("verdana")
then
getPresentation(12)
It’s a kind of chain in which the first link is the request of the “arial” and the last is the presentation request.

AS3 solution

Let’s make it more AS3 like:

1
2
3
4
new Chain( { arg: "arial", command: getFont }, 
                 { arg: "verdana", command: getFont }, 
                 { arg: 12, command: getPresentation }
);
as you see, we need a class called Chain which is responsible for executing commands (in this case requests).

Although it works, I don’t like the syntax very much. We can make it better.

1
2
3
4
5
(new Chain()
		.execute("arial", loadFont)
		.execute("verdana", loadFont)
		.execute(12, getPresentation)
);
Yes, it’s good, looks good, works well.

Parallelism

One more thing, does it support parallelism, It does.

1
2
3
4
5
6
7
8
9
10
11
12
(new Chain()
	.begin
		.execute("arial", loadFont)
		.execute("verdana", loadFont)
		.execute(12, getPresentation)
	.end
	.begin
		.execute("helvetica", loadFont)
		.execute("futura", loadFont)
		.execute(1, getPresentation)
	.end
);

Here you can download the sourecode.

Finally, If I want to sum up how it works, here is an overall figure:
Everything within begin - end happens synchronously, one by one,
and every begin - end pair runs simultaneously.

What do you think?

Finally, there is an interesting article by John Resig about Chaining with JQuery.


This post is tagged ,

No Comments