Here we are again in front of a trick which can be of use to us, actionscripters inveterate.
This time, I would like to write about the call of function from an event.* These events require as a parameter the object's instance which has launched them even if we wanted to call the function without the need to start the event.
It is not really nice and not very educated to need to rewrite another function without implementing the parameter requested.
This little problem could often happen using the Timer Class of Actionscript 3.0 o even working with mouse event.
Follow me and let's get into a practical example' Let's say that we are using the Timer class to call a function every 5 seconds the following way:
Code:
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
var id:int=0;
var timer:Timer=new Timer(5000,0);
timer.addEventListener(TimerEvent.TIMER,go);
timer.start();
function go(t:TimerEvent):void
{
id++;
trace(id);
}
As we can see, this script call the function go() every 5 seconds.
But, as we launch the swf, nothing happens for 5 seconds.
Let's say that this function go() is a function that calls a image in rotation every 5 seconds. When the swf is published, we will have a dead time of 5 seconds.
It would be normal to think to call the function go() right from the start to avoid that problem and then let the timer take over with the 5 seconds interval'but'it is not the way it works!
If we add the function go() before creating an instance of the timer, Flash would return an error, specifying that the number of arguments on call of the function go() is wrong. In fact, the function go() do requires an instance of the TimerEvent class.
At this point, I advise you to do the following way:
Code:
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
var id:int=0;
var fantasma:TimerEvent;
go(fantasma);
var timer:Timer=new Timer(5000,0);
timer.addEventListener(TimerEvent.TIMER,go);
timer.start();
function go(t:TimerEvent):void
{
id++;
trace(id);
}
As you can see, I created an instance of the TimerEvent Class and without initialising it, I passed it to the function go().
This could also happen when we use functions called on a mouse event, such as MOUSE_DOWN of the MouseEvent class, and we would need to call the same function without that mouse event.
See you next !
Bookmarks