addEventListener - one function for multiple events?

How can you set up one function that receives events from different objects on the screen? I don’t want to create a different function every single touch event. Here’s what I have, but it doesn’t work:

[code]
local obj = display.newGroup();

function obj:touch(e)
local t = e.target;

if(e.phase == “ended”) then
print("cat touched: " … t.name);
end
return true;
end
local cat1 = display.newImageRect(“images/cat1.png”, 15, 16);
cat1.name = “cat1”;
obj:insert(cat1);
cat1:addEventListener(“touch”, ???);

local cat2 = display.newImageRect(“images/cat2.png”, 15, 16);
cat2.name = “cat2”;
obj:insert(cat2);
cat2:addEventListener(“touch”, ???);
[/code] [import]uid: 52127 topic_id: 9455 reply_id: 309455[/import]

I am really new to this, but I think if you change your function on line 3 to something like:
local function onTouch(e)

and replace your ??? on your addEventListener(s) to onTouch, it will work.

Since you have the same widtth and height for both newImageRect(s), I think you will only get a touch on cat2, since that is displayed on top of cat1. [import]uid: 47723 topic_id: 9455 reply_id: 34640[/import]

Technically you could do addEventListener(“touch”, obj) each time but that’s kind of bad form because then you’d have an event listener on one object calling a method of another object. I would do it the way flyingaudio suggests, with a local function.

Or rather that’s the approach I would take if I want them all handled in one module. What I normally do is separate the outer group and inner objects into separate modules, have a touch function for each of the inner objects, and that function calls the touch method of the outer group. It’s a level of indirection that helps keep larger projects more organized.

Incidentally, you don’t need to put semi-colons at the end of lines. It doesn’t hurt anything but it’s not necessary either. [import]uid: 12108 topic_id: 9455 reply_id: 34674[/import]