Recently I ran into an issue of functions being called every time scene:show was called, and I was pulling my hair out.
I was creating images in scene:create, and creating functions in scene:show, then addEventListener right below the function in scene:show. This of course added the “tap” listener to the same button every time the scene came on-screen, resulting in the called function being fired multiple times.
It was like this:
-- "scene:create()" function scene:create( event ) local sceneGroup = self.view text = display.newText( "Go To Scene 2", 100, 50, native.systemFontBold, 30 ) text.x = 250 text.y = 100 text:setFillColor(0, 0, 255) trigger = display.newText( "Trigger", 100, 50, native.systemFontBold, 30 ) trigger.x = 250 trigger.y = 300 trigger:setFillColor(0, 255, 0) sceneGroup:insert(text) sceneGroup:insert(trigger) end -- "scene:show()" function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is still off screen (but is about to come on screen). elseif ( phase == "did" ) then print("Scene1 Scene:Show:Did") local function nextScene( event ) composer.gotoScene("scene2") end text:addEventListener("tap", nextScene) local function triggerFunc() print("trigger") return true end trigger:addEventListener("tap", triggerFunc) end end
I solved that issue by moving the listener calls before the images in scene:create but…
I am really unsure about where most functions need to go in the composer template? Is it “right” to have most of the scene functions created and called inside scene:create, OR should most functions be created and called outside the composer functions?
If I try to add listeners after the scene:show and scene:create, it can’t find the images that were created in scene:create. This is important because I have many functions running in the background while other scenes are visited, it may cause a memory hurdle but I can’t imagine it to be that bad.
Thank you, if I didn’t explain my question well please let me know!