开发者

How to remove an anonymous event listener?

So I've run across a problem that has been addressed in other languages but not in Corona/Lua. How does one remove an event listener with an anonymous function?

It would seem that one is supposed to 'store a reference to the function' but I'm not sure of the syntax for that in Lua. I've spent some time looking it up, and the close开发者_如何转开发st match I could find was this answer, which isn't very helpful to me, being in Javascript and all.


Lua has no such thing as "remove event listener". This is handled by libraries/frameworks that use event listeners, in your case Corona. I have no experience with Corona, but have you looked at removeEventListener() documentation?

It seems you just need to save the reference to your listener to be able to remove it later. That is, instead of doing this:

Runtime:addEventListener( "enterFrame", function() ... end )
-- cannot remove the listener, because you have no reference to it

Do this:

-- store a reference to your listener, so that you can remove it
-- equivalent to: local handler; handler = function() ... end
local function handler() Runtime:removeEventListener("enterFrame", handler) end
Runtime:addEventListener( "enterFrame", handler )


Storing the reference to a function is exactly the same as storing a reference to a variable. In order to manipulate an object later you need to give it a name, right? Well, the same goes for functions.

Incidentally, this is only an issue when using a function as the listener. However there's another style of doing event listeners, where you use a table as the listener and then have a function in the table named after the event: http://developer.anscamobile.com/content/application-programming-guide-event-handling#Listeners_and_Event_Delivery

I generally prefer using table listeners.


sorry, above answer is nonsense! do it like this:

local function xyz() blabla end

--or

local xyz = function() blabla end

--add listener

Runtime:addEventListener('enterFrame', xyz)

--remove it again

Runtime:removeEventListener('enterFrame', xyz)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜