PDA

View Full Version : removing event listeners



Alber Kidd
May 25th, 2008, 06:15 PM
I have just found out I can do this





myMovie_mc.addEventListener(MouseEvent.CLICK, function()
{ parent.gotoAndPlay(1);


});





Up untill now I have been creating named functions, this will save a few lines of code, but how do I remove this event listener?

ptfury
May 25th, 2008, 08:09 PM
do this:

myMovie_mc.addEventListener(MouseEvent.CLICK, gotoFunction);

function gotoFunction(event:MouseEvent):void
{
parent.gotoAndPlay(1);
}

i know this has more lines.. but i was always told this is the right way to write it ( but let the experts tell the justice )

ps: i dont know if you can call parent in as3, i think its movieClip(parent).gotoAndPlay ( im not sure because i dont usualy use parent )

to answer your question you can use the removeEventListener just as you use the addEventLisntener, just google it ;)

ps: this helps a lot when we have doubts:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/

snickelfritz
May 26th, 2008, 01:30 AM
Why would you want to remove the click listener?
Just create weak references:


buttonContainer.addEventListener(MouseEvent.CLICK, action, false, 0, true);
buttonContainer.addEventListener(MouseEvent.MOUSE_ OVER, action, false, 0, true);
buttonContainer.addEventListener(MouseEvent.MOUSE_ OUT, action, false, 0, true);

var button:String = "";
function action(event:MouseEvent):void {
button = event.target.name;
switch (event.type) {
case MouseEvent.MOUSE_OVER :
//function here
break;
case MouseEvent.MOUSE_OUT :
//function here
break;
case MouseEvent.CLICK :
//function here
break;
}
}

If you wrap all of your button movieclips in "buttonContainer", this all the code you will need for a virtually unlimited number of buttons.
You can use the button instance name as a test for downstream switch conditionals, since it has been stored within the "button" variable.
ie: if the variable button is equal to "btn1", do something.
It will be equal to the instance name of whichever button you click.

Alber Kidd
May 26th, 2008, 05:47 AM
That looks like an interesting technique but for now....

How do you remove the event listeners in this way. I know how to remove them when calling a function but I cannot get the syntax correct for this method.

Felixz
May 26th, 2008, 08:13 AM
U cant remove anonymous listener.
But:
function action(event:MouseEvent):void {
event.currentTarget.removeEventListener(MouseEvent .MOUSE_OUT, action);
}

amarghosh
May 27th, 2008, 03:55 AM
u can remove anonymous listeners from within the listener function:

mc.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void
{
trace("anonymous method called");//this will traced only once - during the first click;
parent.gotoAndPlay(1);
mc.removeEventListener(MouseEvent.CLICK, arguments.callee);
});