简体   繁体   中英

corona sdk. addEventListener “tap” to many instances of a class

I have this 2 dimensional array of instances of a class (which is mainly just a bit of text) I'd like to add...

         addEventListener("tap", functiontocall)

to all the instances (so when you tap on one it changes colour and stuff) Ive tried adding this in a few places and none of them worked.. In the class itself, in the class contructor function, and in my loop which generates the array. Any ideas? Heres the for loop btw...

    mainarray = {}

    for x = 1, 5, 1 do
    mainarray[x] = {}

    for y = 1, 5, 1 do
    mainarray[x][y] = diceclass.new(x,y)
            --mainarray[x][y].dicetext:addEventListener("tap", bloop)  I tried this and it didnt work.
    end
    end

Strangely if I put these in later they actually work! But it doesnt work in my loop...

    mainarray[1][1].dicetext:addEventListener("tap", bloop)
    mainarray[1][2].dicetext:addEventListener("tap", bloop)

So I could add in 25 lines of code! Though apart from being silly this would not be good as I ultimately want the event to trigger a function within the specific object itself.

Try the following code. This may help you:

local mainarray = {}
for x = 1, 5, 1 do
mainarray[x] = {}      -- See where it is initialized --
for y = 1, 5, 1 do
    mainarray[x][y] = display.newText(x.."|"..y,10,10,nil,10)
    mainarray[x][y].x = 20+math.random(300)
    mainarray[x][y].y = 20+math.random(460)
    mainarray[x][y].tag = x.."|"..y
end
end

local function printTag(e)
    print(e.target.tag)
    return true;
end
for x = 1, 5, 1 do
for y = 1, 5, 1 do
  mainarray[x][y]:addEventListener("tap",printTag)
end
end

Keep Coding........... :)

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