Is this the correct way to define and remove the eventListener?

I want to use a native text field with the storyboard.   Here’s a cut down version of the code.

First I have a forward definition of my text field and listener function

[lua]
local txtGuitar, fieldHandler
[/lua]

Then in my enterScene I create the text field and event listener.   It works, life is good.

[lua]

function scene:enterScene( event )

local group = self.view

function fieldHandler( event )

print(event.phase)

if ( “began” == event.phase ) then
– This is the “keyboard has appeared” event
– In some cases you may want to adjust the interface when the keyboard appears.

elseif ( “ended” == event.phase ) then
– This event is called when the user stops editing a field: for example, when they touch a different field

elseif ( “submitted” == event.phase ) then
– This event occurs when the user presses the “return” key (if available) on the onscreen keyboard

– Hide keyboard
native.setKeyboardFocus( nil )

end
end

txtGuitar = native.newTextField( 10, 50, display.contentWidth - 20, 30 )
txtGuitar:addEventListener( “userInput”, fieldHandler)

end

[/lua]

Then in my exitScene I want to remove the event listener and clean up the text field:
 

[lua]
function scene:exitScene( event )

local group = self.view

txtGuitar:removeEventListener( “userInput”, fieldHandler)

if txtGuitar then
txtGuitar:removeSelf()
txtGuitar = nil

end
end

[/lua]

Is that correct?  i.e. I should have a forward definition of the listener?  Is this code correct or would it leak memory?  THANKS!!!

You don’t need to remove the listener.  When you remove the text field, it will take care of removing the listener for you.

Since you’re not putting the word “local” in front of your handler function, it’s global and would overwrite other functions with the same name.  I would also move it outside of your enterScene() function and put it in the scene’s main chunk.  But the rest looks about right.

Thanks.   

You don’t need to remove the listener.  When you remove the text field, it will take care of removing the listener for you.

Since you’re not putting the word “local” in front of your handler function, it’s global and would overwrite other functions with the same name.  I would also move it outside of your enterScene() function and put it in the scene’s main chunk.  But the rest looks about right.

Thanks.