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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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", ???);

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.

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.

views:1599 update:2011/10/2 9:44:12
corona forums © 2003-2011