Is it possible to put a listener function inside of an object module?
I have a Cloud class that implements a Display Object. Right now, the class only creates the image. I'd like it to also be in charge of its own listener event, so that I do not need to keep calling the addEventListener per object I spawn.
I've tried several variations, and I always end up with the listener function as nil. I've also tried splitting it out so that the addEventListener function is called in the main.
I'm starting to get the feeling that listener functions in objects aren't supported. Maybe I'm taking the wrong approach to this? Is what I'm asking feasible? And if yes, what am I doing wrong?
--
-- Cloud.lua
--
local Cloud = {}
local mtaCloud = { __index = cloud } -- metatable
local display = require "display"
-- DOESN'T WORK
function Cloud.scroll( event )
img.y = img.y - img.scrollSpeed
if (img.y + img.contentWidth) < 0 then
img.x = 0
img:translate( math.random(1,_W), 1800 )
end
end
function Cloud.New( strImage, intHeight, intWidth, intScrollSpeed)
local image = display.newImageRect( strImage, intWidth, intHeight )
image.anchorX = 0; image.anchorY = 0.5;
image.x = _W/2; image.y = _H/2;
image.scrollSpeed = 10
image.enterFrame = scroll
Runtime:addEventListener("enterFrame", scroll)
local newCloud = {
img = image
}
return setmetatable( newCloud, mtaCloud )
end
return Cloud
-- main.lua (simplified)
local cloud = require "object.cloud"
function scene:create( event )
local group = self.view
cloud = cloud.New("img/cloud.png", 230, 140)
group:insert(cloud.img)
end