object:addEventListener()

Type Function
Object EventListener
Library none
Return value none
Revision Current Public Release (2014.2511)
Keywords addEventListener, event listener
See also object:removeEventListener()

Overview

Adds a listener to the object’s list of listeners. When the named event occurs, the listener will be invoked and be supplied with a table representing the event.

Syntax

object:addEventListener( eventName, listener )
eventName (required)

String. String specifying the name of the event to listen for. Please refer to the Events documentation for valid event names.

listener (optional)

Listener. Listeners can be either functions or table objects. If the event's event.name matches this string, the listener will be invoked. Event listeners are either functions or objects (table listeners). This argument is optional if it's a table listener of the same object.

Example

local object = display.newImage( "image.png" )

function object:touch( event )
    if event.phase == "began" then
        print( "You touched the object!" )
        return true
    end
end

object:addEventListener( "touch", object )

Gotchas

You cannot add an object event listener within the listener event for that object. You should add the listener event outside of the current listener using the timer.performWithDelay() API. Failing to do so will cause the new listener to be called immediately after the current listener returns.

Another solution to the problem is using a single event listener for the object and adding a "state" variable to control what function is performed when invoked.

local addListener1, addListener2

-- Create a large button
local rect = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
rect:setFillColor( 1, 0, 0 )

-- State 1
function state1Cb( event )
    print("state1")
    rect:removeEventListener( "tap", state1Cb )
    --rect:addEventListener( "tap", state2Cb )  -- Do NOT do this!
    timer.performWithDelay( 1, addListener2 )   -- Do this instead
    return true   
end

-- State 2
function state2Cb( event )
    print("state2")
    rect:removeEventListener( "tap", state2Cb )
    --rect:addEventListener( "tap", state1Cb )  -- Do NOT do this!
    timer.performWithDelay( 1, addListener1 )   -- Do this instead
    return true   
end

function addListener2( )
    rect:addEventListener( "tap", state2Cb )
end

function addListener1()
    rect:addEventListener( "tap", state1Cb )
end

-- start
addListener1()  -- Add first listener