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:

callBack=callback;

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:


typeOfMessage=1;


callback(typeOfMessage);

2 comments:

  1. Just wanted you to know I really appreciated you taking the time to post this it really help me with a problem I was have with a program I bought that use callbacks. In my class it would not see it till I made it public and reference the way you did. Thanks again.

    ReplyDelete
  2. @Anonymous. Thank you! This might interest you. I made a new article just now about Custom Events. You might want to get a look at that since it's more efficient and after setting everything up, you can do the same with event listeners. The article is here: http://as3snippets.blogspot.ie/2012/06/custom-events.html

    ReplyDelete