you’re close, but just need to perhaps formalize/generalize the process a little bit.
you create a closure as you have done, but you will need to save that on your object for use later, on ‘removeEventListener’.
i have this function in my utilities module to create closures for object-callback as required:
-- createObjectCallback() -- Creates a closure used to bind a method to an object. Useful for creating a custom callback. -- -- @param object the object which has the method -- @param method the method to call -- function Utils.createObjectCallback( object, method ) if object == nil or method == nil then error( "ERROR: missing object or method in createObjectCallback()" ) end return function( ... ) return method( object, ... ) end end
here’s an example of its use:
function YourObject:setup() self.\_callback = Utils.createObjectCallback( self, self.runtimeEventHandler ) -- \<\< Runtime:addEventListener( 'accelerometer', self.\_callback ) end function YourObject:teardown() Runtime:removeEventListener( 'accelerometer', self.\_callback ) self.\_callback = nil end function YourObject:runtimeEventHandler( event ) -- this method will now get runtime events -- in context of instances of YourObject end
since i use this so much, i added it as a class method to my OOP library:
-- in OOP hierarchy function Object:createCallback( method ) if method == nil then error( "ERROR: missing method in createCallback()", 2 ) end return function( ... ) return method( self, ... ) end end
this style makes the callback creation a littler simpler, but everything else is the same:
function YourObject:setup() self.\_callback = self:createCallback( self.runtimeEventHandler ) -- \<\< note use of : and . Runtime:addEventListener( 'accelerometer', self.\_callback ) end function YourObject:teardown() Runtime:removeEventListener( 'accelerometer', self.\_callback ) self.\_callback = nil end function YourObject:runtimeEventHandler( event ) -- this method will now get runtime events -- in context of instances of YourObject end
HTH
cheers,
dmc