Corona SDK Pro Tip of the Day #25
Finalize event

Finalize event is extremely useful for developing. If you are familiar with C++ or other classic OOP languages, you can think about finalize event as a destructor - something that happens when a Corona Display Object is destroyed.

I use it all the time. Mostly for cancelling transitions or timers that a particular object uses.

local circle = display.newCircle(group, 100, 100, 10)

function circle:animate()  
    self.t = transition.to(self, {time = 1000, alpha = 0})
end

function circle:finalize()  
    -- This is called on circle:removeSelf() or display.remove(circle)
    if self.t then
        transition.cancel(self.t)
    end
end

circle:addEventListener('finalize')  

That would be completely a breeze to implement, if only it actually worked properly in Corona.

The problem is that this doesn't work if you are removing a group that contains something with finalize event in it.

But don't panic! There is a workaround for now until Corona team fixes this issue.

Put this code somewhere before you create any groups. I keep it inside app.lua.

-- Fix problem that finalize event is not called for children objects when group is removed
local function finalize(event)  
    local g = event.target
    for i = 1, g.numChildren do
        if g[i]._tableListeners and g[i]._tableListeners.finalize then
            for j = 1, #g[i]._tableListeners.finalize do
                g[i]._tableListeners.finalize[j]:dispatchEvent{name = 'finalize', target = g[i]}
            end
        end
        if g[i]._functionListeners and g[i]._functionListeners.finalize then
            for j = 1, #g[i]._functionListeners.finalize do
                g[i]._functionListeners.finalize[j]({name = 'finalize', target = g[i]})
            end
        end
        if g[i].numChildren then
            finalize{target = g[i]}
        end
    end
end  
local newGroup = display.newGroup  
function display.newGroup()  
    local g = newGroup()
    g:addEventListener('finalize', finalize)
    return g
end  

This fix hacks into display.newGroup() function, replacing it with a version that actually does honor finalize listeners of it's children.

Indie Game Developer