Oh, and let’s clarify some terms.
-
The function’flip’ that you added to ‘instance’ is a method because it implies the argument ‘self’
-
You are trying to set up a custom event listener for an event named ‘flip’
-
You have implied you want to listen for and to dispatch this event in the Runtime (global) space.
-
Alternately, you could dispatch this directly via the object space, but that would be redundant with my example above where I suggest calling the method directly.
Tip: This last point is why I never use the object event dispatch system (except in extremely specialized cases.) You need the object to be in scope to dispatch in the object space so why not call the method directly?
The power of Runtime events combined with custom event listeners is that you can send ‘events’ into the global space and objects will respond to them, never needing to be directly connected to the calling code or its scope.
There is a danger here too. Objects with custom event listeners that are listening in the Runtime space can receive events after the object has been destroyed but not yet removed from the Lua memory system. Thus you may try to manipulate a display object property of a ‘dead’ object. This will cause a crash.
I solve this in one of two ways:
- I use a finalize event to remove all runtime listeners from objects.
- I add validation code at the top of the custom event listener to ensure the object I’m about to operate on is valid otherwise I stop listening for the event.
As always, SSK comes with handy helpers for all of this…
Standalone example modified with finalize solution:
require "ssk2.loadSSK" \_G.ssk.init() local rect = display.newRect( 100, 100, 100, 100 ) function rect.onFlip( self, event ) table.dump(event) transition.cancel( self ) transition.to( self, { rotation = self.rotation + 45 } ) end; listen( 'onFlip', rect ) function rect.finalize( self ) ignoreList( { 'onFlip' }, self ) end; rect:addEventListener("finalize") local function onTouch( event ) if( event.phase == "ended" ) then post('onFlip') end end listen( "touch", onTouch ) display.remove( rect )
Standalone example above with validation code in event listener:
require "ssk2.loadSSK" \_G.ssk.init() local rect = display.newRect( 100, 100, 100, 100 ) function rect.onFlip( self, event ) if( autoIgnore( 'onFlip', self ) ) then return end table.dump(event) transition.cancel( self ) transition.to( self, { rotation = self.rotation + 45 } ) end; listen( 'onFlip', rect ) local function onTouch( event ) if( event.phase == "ended" ) then post('onFlip') end end listen( "touch", onTouch ) display.remove( rect )