I have wondered for some time why Corona allows duplicate listeners of the same name/type, and so far I haven’t figured out why this should be possible.
Assume the following code. I intentionally add two Runtime “enterFrame” listeners that call the same function. If you run this code, you’ll notice that removing the listener (after the timed delay) effectively only removes one of them, and so the listener keeps going.
local function running()
print("RUNNING")
end
local function removeIt()
print("REMOVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
Runtime:removeEventListener( "enterFrame", running )
end
Runtime:addEventListener( "enterFrame", running )
Runtime:addEventListener( "enterFrame", running )
timer.performWithDelay( 2000, removeIt )
Obviously this is a silly example, because there should be no reason to add two duplicate listeners. But in the shuffle of programming, in a complicated scenario, it’s not far-fetched at all to imagine 2 duplicate listeners called, resulting in problems/errors and debugging headaches. Imagine a scenario where a collision event triggers a Runtime listener; if two of these collisions occur, or if the phases are not checked carefully, you will end up with multiple listeners running when, most likely, only one is desired.
The same goes for other types of listeners, as far as I know. For example, the most simple touch listener on an object “button” which calls the function “buttonPress” and then performs some action:
button:addEventListener( "touch", buttonPress )
This is all fine unless you want to manage whether the button is active or not, by removing and re-applying its listener. Or when you want to perform a comprehensive cleanup function to remove all listeners, i.e. between levels. If for some reason this button listener was added twice, then there’s a stray hanging out there likely causing problems.
Clearly, there are ways to avoid duplicating listeners (boolean variables with if-then statements, etc.). First and foremost, it’s the programmer’s responsibility to write clean code. However, as a fail-safe, why can’t Corona simply prevent duplicate listeners entirely? If you have a button with a touch listener, well… you have a button with a touch listener! The type (“touch”) and the target function (“buttonPress”) dictates that the button has that specific listener applied. If another addEventListener
call is made using the same type and function , Corona should simply ignore it. This would spare us some debugging nightmares when, as I said, duplicate listeners are unintentionally applied. Furthermore, I see no instance when multiple listeners of the same type/function are necessary… and if they never are, but the alternative can cause problems, then Corona should not allow it.
Thoughts or opinions? Notch a +1 if you agree with this fix for a future release of Corona.
Thanks,
Brent Sorrentino
Ignis Design [import]uid: 9747 topic_id: 19153 reply_id: 319153[/import]