Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does addEventListener (and removeEventListener) stack?

Given the below:

object.addEventListen(eventType01,handler01);
object.addEventListen(eventType01,handler01);

object.removeEventListener(eventType01,handler01);

How many event listeners for eventType01 are on object? One or zero?

like image 853
ThatSteveGuy Avatar asked Apr 28 '11 20:04

ThatSteveGuy


1 Answers

Zero. If you call addEventListener, using the exact same arguments more than once all subsequent calls after the first "silently fail." Call add as many times as you want, but that single remove will wipe the listener away.

EDIT: Another thing to keep in mind is that there's no penalty to calling multiple identical removeEventListener() functions on the same object, aside from needless performance overhead. No deadly error will occur, it will simply "silently fail" much the same way as repeated identical addEventListener calls will.

EDIT 2: To answer @ThomasM :: if your listener "fires twice" then you do not have exactly the same listener. Try putting this quick and dirty code on frame 1 in a fla that has one square movieclip as a child:

import flash.events.*
function foo(e):void{
    trace("hi");
}

this.addEventListener(MouseEvent.CLICK,foo);
this.addEventListener(MouseEvent.CLICK,foo);
this.addEventListener(MouseEvent.CLICK,foo);

Notice that your output when you click the movieclip is precisely one trace action.

Now add this line to the end of the code

this.removeEventListener(MouseEvent.CLICK,foo);

Even though you added foo as a listener for click 3 times, this one call kills the listener completely.

So if you're experiencing an issue where "the same listener" fire twice then probably what you're doing is something like this:

this.addEventListener(MouseEvent.CLICK, function(e){
    trace("hi");
});

this.addEventListener(MouseEvent.CLICK, function(e){
    trace("hi");
});

That will definitely "fire twice" because the listener functions ARE NOT THE SAME. They perform the same actions but they do not reference identical positions in memory. They do not point to the same function object. Furthermore this is highly bad practice because you have no way to actually remove those listeners. How would you do it? You have no reference to them.

like image 101
scriptocalypse Avatar answered Oct 25 '22 00:10

scriptocalypse