Friday, 13 August 2010

Function Call Back

This is very handy feature when programming in AS3.

Imagine that you make a AlertBox class, that when called, it makes a custom Alert message. Imagine then, that you can put 1, 2 or 3 buttons, according to the message type. 

If you want to reuse this class in several projects, it's a good idea to tell the different buttons what or where to return when it's pressed.

That's were the Function Call Back enters. After a couple of hours and some search in the web, I came up with a solution, which I want to share.

It's very simple.
First declare in your class a variable that will keep the function reference later on, like this:

private var callBack:Function;

Then when you instantiate the Class, one of the arguments, of the constructor or function, will keep the function name, like this:

createAlert(..., callback){

Finally inside the constructor or function, you have to attribute the argument to the variable you defined earlier, like this:


Then place this variable as a call of some event, like this:

button1.addEventListener(MouseEvent.CLICK, callBack);

... and that's it.

If you want to call the call back function with arguments, instead of a event, just call this way: