Creating Custom Events in Flash
Had to create an event for a project I’m working on, and after a search I found that you can indeed accomplish this within Flash using an undocumented AS class.
I read about it here and here.
The basic gist is that you create an object, you convert that object into an actual broadcaster via the AsBroadcaster class. Then you register listeners just as you would for any native event, and you can pick up the event.
So say you wanted to create a custom event for keeping track of when someone was logged in, or logged out, so you could perform various tasks depending on where they are in the application.
So first you set up your new event broadcaster object:
var loginStatus:Object = new Object();
AsBroadcaster.initialize(loginStatus);
Then when a user logs in, you would register your custom event:
loginStatus.broadcastMessage(”onLoggedIn”);
Or if they were to log out, you would register that custom event:
loginStatus.broadcastMessage(”onLoggedOut”);
And where you need actions to be performed for this event, you create the listener:
var loginStatusListener:Object = new Object();
loginStatusListener.onLoggedIn = loggedIn;
loginStatusListener.onLoggedOut = loggedOut;
loginStatus.addListener(loginStatusListener);
function loggedIn() {
trace(”loggedIn()”);
}
function loggedOut() {
trace(”loggedOut()”);
}
Then if you need to clear the listener at any point you can use:
loginStatus.removeListener(loginStatusListener);
And just pass in the name of the listener object you wish to unsubscribe from the broadcast.
Tags: AsBroadcaster, flash, actionscript, custom, event