As3 event management

Recently while working on an as3 project the project manager of the project came over to me and asked that something happen automatically that was currently happening only on a mouse click. Normally I would have said fuck you that is impossible and get the hell out of my face. I was feeling confident today though with the event model of as3 so I said yeah I think we can make that happen. The logic was that at worst I would have to make a separate function based on the one I already had. So in a quest to solve this problem I offer you the most awesome kick ass thing you could ask for.

With as3 you quite literally fake an event. And you can do so very easily. All you need to do is import the events classes:


Then any time you have a button you can fake whatever event you want. You can fake all sorts of events not just button. But faking a click is often the most useful. The code for doing such a thing is as follows.

// note you must make a symbol and link it in order to make an instance.
function init(){
	mybutton = new customSymbolIHaveLinked();
	mybutton.mouseChildren = false;
	mybutton.mouseEnabled = true;
	// this makes the button listen for the click event
	mybutton.addEventListener(MouseEvent.CLICK, functiontorun);
	// now if you would like to automatially run this event on start up to perhaps ensure the user is at a default
	// position you simply need to dispatch an event
	mybutton.dispatchEvent(new Event(MouseEvent.CLICK));
function functiontorun(evt:Event){
	trace("recieved event from ";

That’s all there is to it really. I hope this has been helpful. It has been a lifesaver for me. Thanks again as3 for making life a hell of a lot easier…

  • Rich

    Another way to execute an event listener function, without the originally intended event, is to pass in null. You can just replace line 12 above with functiontorun(null); Nice blog, thanks!

  • jeff

    Your correct. However it should be noted that then your target will be null. Thus if you you perform an action on the button onclick then this ability will be lost by passing null

  • mike

    Hey – I came across this, but couldn’t get it to work. Eventually I came up with this code, though, which is a bit simpler and does what I want it to:

    //I add the stage listener just before any of my button listeners

    stage.addEventListener(Event.ENTER_FRAME, initfunction)
    function initfunction(e:Event):void{
    buttonName.dispatchEvent(new MouseEvent(MouseEvent.CLICK,true));
    stage.removeEventListener(Event.ENTER_FRAME, initfunction);

    //I remove the event listener in its own function – if it just needs to click, then it can go away as soon as it comes in