简体   繁体   中英

addEventListener() in Lua

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!

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))

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.

eg, 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.

And you can add events to any lua table using the following class:

https://github.com/open768/library/blob/master/lib/lib-events.lua

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM