Corona SDK:addEventListener 在错误的时间调用方法。

我正在尝试向一个半透明黑色背景添加事件监听器,调用 cancel 方法,使用以下代码:

blackRect = display.newRect(display.contentWidth/2,
                            display.contentHeight/2,
                            display.contentWidth,
                            display.contentHeight)
blackRect:setFillColor(0)
blackRect.alpha = 0.9

local function cancel( ... )
    if blackRect then
        blackRect:removeSelf()
        blackRect = nil
    end
    if yesBtn then
        yesBtn:removeSelf()
        yesBtn = nil
    end
    if cancelBtn then
        cancelBtn:removeSelf()
        cancelBtn = nil
    end
    if getCoinsBtn then
        getCoinsBtn:removeSelf()
        getCoinsBtn = nil
    end
    if notEnoughCoins then
        notEnoughCoins:removeSelf()
        notEnoughCoins = nil
    end
    -- Body
end

blackRect:addEventListener("tap", cancel)
blackRect:addEventListener("touch", cancel)

然而,当我调用addEventListener时,cancel 方法被调用,或者至少看起来是这样,因为blackRect甚至没有显示在屏幕上,其他在上面代码后创建的对象也是如此。

点赞
用户3580814
用户3580814

你的问题有点混乱。你说“当我调用addEventListener时,cancel方法被调用”,这实际上是有意义的,你是指“cancel方法没有被调用”吗?

我测试了你的代码的简化版,它可以正常工作:

local blackRect = display.newRect(display.contentWidth/2,
                                  display.contentHeight/2,
                                  display.contentWidth,
                                  display.contentHeight)
blackRect:setFillColor(0)
blackRect.alpha = 0.9

local function cancel()
    print("executing cancel")
    if blackRect then
        print("removing blackRect")
        blackRect:removeSelf()
        blackRect=nil
    end
end

blackRect:addEventListener("tap", cancel)
blackRect:addEventListener("touch", cancel)

当我点击黑色矩形框时,事件监听器被激活并且对象被删除。我添加了一些打印语句,可以在控制台中查看到它确实执行了。

2014-04-28 10:19:00