问题
I have a problem when work with Corona and need a help.
When I register an event listener, such as object:addEventListener("touch", listener)
. But listener function has many parameters like this:
function listener (event, param1, param2...)
...
end
My question is that how to pass all of parameters to listener. All search only pass one para is event.
Thanks!
回答1:
local function listener(param1, param2)
return function(event)
print(event.name, event.phase, param1, param2)
end
end
Runtime:addEventListener("touch", listener(12, 33))
Runtime:addEventListener("tap", listener(55, 77))
回答2:
One way to do this is to just add properties to the object to which you attach the handler. In the listener, you can access them through the event.target
parameter.
e.g., adding new param1
and param2
properties to some image objects:
local touchHandler = function( event )
if event.phase == "began" then
local t = event.target
print( "param1=" .. t.param1 .. ", param2=" .. t.param2 )
end
end
local image1 = display.newImageRect( "myImage.png", 100, 100 )
image1.param1 = "Apple"
image1.param2 = "Zucchini"
image1:addEventListener( "touch", touchHandler )
local image2 = display.newImageRect( "myImage.png", 100, 100 )
image2.param1 = "AC/DC"
image2.param2 = "ZZ Top"
image2:addEventListener( "touch", touchHandler )
This will print "Apple" and "Zucchini" when you touch image1, and print "AC/DC" and "ZZ Top" each time you touch image2.
回答3:
And you can add events to any lua table using the following class:
https://github.com/open768/library/blob/master/lib/lib-events.lua
来源:https://stackoverflow.com/questions/8276127/addeventlistener-in-lua