Reputation: 2231
In one class, I have 2 "buttons" which are calling 2 classes like so:
btn1 = display.newImage("1.png")
btn2 = display.newImage("2.png")
btn1:addEventListener("touch", onSceneTouch)
btn2:addEventListener("touch", onSceneTouch2)
The problem with this is that the 2 methods (onSceneTouch, onSceneTouch2) do the same thing. The only difference is that it sets a flag depending on which button is touched. My methods look like this:
function onSceneTouch( event )
//do something here
end
I've tried searching and I found this article and tried to follow it. I added an id to the buttons and called them on my method but the id was nil. If I try to set a name for the button instead like: btn1.name = "name" and call self.name on my method but of course, the name returned "touch". How would I tell my method which button was touched?
Upvotes: 0
Views: 1642
Reputation: 998
enter code here
Use single event listener & identify who called this using unique name
eg
function onSceneTouch( event )
local objectName=event.target.name
if objectName==1 then
flag1=true
else
flag2=true
end
end
btn1 = display.newImage("1.png")
btn1.name=1
btn2 = display.newImage("2.png")
btn1.name=2
btn1:addEventListener("touch", onSceneTouch)
btn2:addEventListener("touch", onSceneTouch)
Upvotes: 0
Reputation: 3063
I know answer 1's example should work just fine, but it's a bit more work than doing a function listener instead of a table listener. I would have written it like this:
function onSceneTouch(event)
local target = event.target -- this is the actual button that was touched.
if event.phase == "ended" then
-- do your work here
print(target.id) -- prints "Button1" or "Button2"
end
return true -- important!
end
btn1 = display.newImage("1.png")
btn2 = display.newImage("2.png")
btn1.id = 'Button1'
btn2.id = 'Button2'
btn1:addEventListener("touch", onSceneTouch)
btn2:addEventListener("touch", onSceneTouch)
Same thing different way.
Upvotes: 1
Reputation: 23767
According to the article you linked to, your code should look like this:
function onSceneTouch(self, event)
local button_id = self.id
--do something here
end
btn1 = display.newImage("1.png")
btn2 = display.newImage("2.png")
btn1.id = 'Button1'
btn2.id = 'Button2'
btn1.touch = onSceneTouch
btn2.touch = onSceneTouch
btn1:addEventListener("touch")
btn2:addEventListener("touch")
Doesn't it work?
Upvotes: 2