Why doesnt this work (event.target)

Hi, I’m trying to dynamically generate a series of image objects on the screen and then have an event listener find out which one was clicked. I got as far as the code below but even that doesn’t work. Any pointers very welcome.

[lua]local button = display.newImage(“button.png”);
button.x = display.contentWidth/2;
button.y = display.contentHeight -50;

local function what_was_tapped(event)
print(event.target);
end

Runtime:addEventListener(“tap”, what_was_tapped);[/lua] [import]uid: 55068 topic_id: 10737 reply_id: 310737[/import]

The button isn’t part of the event, it’s not the target, it’s just an image.

It’s like if you put ten images on top of each other and only add a listener to image1, even if that image is on the bottom, “image1” will print.

Peach :slight_smile: [import]uid: 52491 topic_id: 10737 reply_id: 38958[/import]

Thanks Peach

So I guess the next question is: how do you add event listeners to dynamically generated objects on screen?

Cheers

Tom [import]uid: 55068 topic_id: 10737 reply_id: 38959[/import]

What platform are you compiling for? I remember reading about a bug in Android builds where “tap” does not work. You might want to try using “touch” instead. I seem to remember that it says somewhere in the Corona Docs that you should avoid using underscore in function and variable names (although I could be misremembering so take it with a grain of salt). [import]uid: 27965 topic_id: 10737 reply_id: 38960[/import]

Wow - I’m so stooopid :wink:

[lua]local function wasTouched(event)

print(“cicked”);

end

local function spawnNewImage()
button = display.newImage(“button.png”);
button.x = math.random(50, 200);
button.y = math.random(50, 400);
button:addEventListener(“touch”, wasTouched);

end

spawnNewImage();[/lua]

Didn’t realise you could add an event listener INSIDE of a function…

Thanks

Tom [import]uid: 55068 topic_id: 10737 reply_id: 38961[/import]

Thanks for posting your findings! Glad you figured it out. [import]uid: 27965 topic_id: 10737 reply_id: 38967[/import]

@Tom, awwww, don’t say mean things about yourself! (Besides, personal attacks are against forum rules ;))

It’s not stupid; it’s a learning curve. Rather than thinking “I’m silly for not knowing that!” you should think, “I’m awesome for learning something new and useful today!”

Glad it’s all sorted!

Peach :slight_smile: [import]uid: 52491 topic_id: 10737 reply_id: 39143[/import]