addEventListener() in Lua

淺唱寂寞╮ 提交于 2019-12-14 03:57:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!