Execute Commands on queue

The AS3 Utility Class to add commands in a queue, the usage and class is below:

/** 
* var commands : CommandsQueue = new CommandsQueue();
* commands.addCommand( this, myFunc );
* commands.addCommand( this, myFunc2, [0,2], this, Event.COMPLETE );
* commands.execute();
*/
package
{
import flash.events.Event;
import flash.events.EventDispatcher;

public class CommandsQueue extends EventDispatcher
{
protected var commands : Array;
protected var _index : Number = 0;
public var onComplete : Function;

public function CommandsQueue():void
{
commands = [];
}
public function addCommand( thisObj : Object, func : Function, params: Array = null , completeEventDispatcher : Object = null, completeEventName : String= null ) : void
{
commands.push({
thisObj : thisObj,
func : func,
completeEventDispatcher : completeEventDispatcher || thisObj,
completeEventName : completeEventName,
params : params
})
}
public function get progress():Number
{
return (commands.length>0)? _index / commands.length * 100 : 0;
}
public function cancel() : void
{
throw new Error(“commandQueue.cancel is not implemented yet”);
}
public function execute() : void
{
doNext();
}
public function get index():int
{
return _index;
}
public function get length():int
{
return commands.length;
}
protected function doNext() : void
{
var act : Object = commands[ _index ];

if( act.completeEventName ){
act.completeEventDispatcher.addEventListener(act.completeEventName, _commandComplete, false, 0, true);
act.func.apply( act.thisObj, act.params );
} else {
act.func.apply( act.thisObj, act.params );
doNextCommand();
}
}
protected function doNextCommand() : void
{
var act : Object = commands[ _index ];

if( act.completeEventName )
act.completeEventDispatcher.removeEventListener(act.completeEventName, _commandComplete);

_index ++;

if( _index == commands.length )
{
commands = []; //remove all registerd command for GC
if( onComplete != null )
onComplete();
dispatchEvent( new Event(Event.COMPLETE) );
}else{
doNext();
}
}
protected function _commandComplete( e : Event ) : void
{
doNextCommand();
}
}

    • Xerios
    • December 30th, 2008

    Thanks , exactly what I’ve been searching for😀

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: