Arieh.co.il

Introducing Function Stack

What Is FunctionStack?

FunctionStack is a simple mootools Class designed to define a sequence of function calls and the delay between them. I've created it while debugging another Class - TreeAccordion (which I'll probably write about another time).

Here is a simple usage example:

function a(){console.log('a');}
function b(){console.log('b');}
function c(){console.log('c');}

var stack = new FunctionStack(a,b,c);
stack.step(); //a
stack.play(2000);//b,c with a 2sec delay between them

This might look a bit of an odd use case, but if you will look here in the javascript tag you can see that I used the class to define a use case for the library's behavior. This can be (and has been) extremly useful when testing and debugging your application's interface.

Some common uses for it:

  1. You can use it to automate behavioral testing.
  2. You can use it to pass the stack between colaborating Classes.
  3. You can use it to create effect chains (though this could be done in other manners).

But there's more!

FunctionStack also comes with additional functionality:

  1. It can be used as a periodical caller - which is great for automated testing.
  2. It allows you to pass arguments to the functions in the stack.
  3. If using the step method, it returns the value of the called function.

Using the stack with arguments:

function a(str){
    console.log('a:' str);
}

function b(str){
    console.log('b:' str);
}

var stack = new FunctionStack(a,b);
stack.step('aaa');//a:aaa
stack.step('bbb');//b:bbb

stack.reset();
stack.play(300,'ccc'); //a:ccc - b:ccc

Again - this is just a usage example. I trust your creativity to find better usages for the class.

But doesn't Mootools already have a Chain Class for this?

Well, not realy. Mootools supplies a Class extra for you to implement called Chain, that allows you to define chaining behavior for your class, but isn't by itself a usable Class. Just look at Chain's docs to see it used to create something close to my implementation.

There are a few key differances between the two - which are summarized at the Forge page:

  1. It is ment to be used as a periodical caller - the play method.
  2. It is posible to pass arguments to the functions in the stack.
  3. It is ment to be used as a standalone, not to be implemented by other classes. Class method names are trivial and probably will be needed by implementors (push, play, clear, reset, stop, pause).
FunctionStack Forge page

Links

  1. Forge Page.
  2. Usage example at TreeAccordion's demo.
  3. Docs
JavaScript Reference, JavaScript Guide, JavaScript API, JS API, JS Guide, JS Reference, Learn JS, JS Documentation