Function listeners in Corona

Introduction :
Listeners are generally used to do some job against any event associated with an object. There are different ways to define listeners. On  below I will describe about one of them.

Description : In corona, repective listeners are being called, when an event get triggered. Basically there are two different ways to define listeners. One is ‘function listeners’ and another is ‘table listeners’.

To describe function listener, lets make a situation, where we will have a rectangle and onClick of that, we will display a message to console.

CODE BLOCK :

 
main.lua
local myBox = display.newRect( 100, 100, 200, 100)

On above, I have defined a rectangle using newRect function which accepts four parameters.
The first and second parameter hold the x and y cordinates as the base postion for the box and the next two parameters define the width and height respectively.

myBox:setFillColor( 121, 121, 121 )
      -- Define the background color of the box.
 
-- Define function listener for the box
local function functionListener( event )
 
   -- Print on consele
   print( 'Function listener called!' )
 
end

Here on above a function is defined which will print message on console.

myBox:addEventListener( 'touch', functionListener )
 -- Listener added with touch event

Now on touch of the above rectangle the ‘functionListener’ will be called every time

Summary :
Here we have an example, how to bind function listener with any display object.

NOTE : Tested in iOS and Android device.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!