2
votes

Is there a way to detect that the displayed object is being removed? Something like:

obj:addEventListeren("before_remove", function(ev)
    -- ev.target will be removed soon
end);
2
Do you want to detect before the object is being removed (as in your example) or you just want to know if a object does not exist anymore? - rsc
Ideally I would like to have callback before object is removed, but checking if object does not exist anymore will do too. - iBad

2 Answers

1
votes

Do you want to check for the existence of an object before removing it? Then you can check for any of the major properties of that object with nil. Like below:

local rect = display.newRect(50,50,100,50)  -- Creating an object

local function myFunction(e)
  if(rect.x~=nil)then  -- checking for its presence    
    print("Object exists. So, remove it...")         
    rect:removeSelf()
  end
end
Runtime:addEventListener("tap",myFunction).

Keep Coding.............. :)

1
votes

I have done it, but implementation relays on Corona SDK internal implementation and can stop working without notice. Looks something like this:

function AddDestructor(obj, func)
    obj._isWidget = true;
    if (not obj.originalRemove) then
        obj.originalRemove = obj.removeSelf or (function() end);
        obj.removeSelf = function(self)

            for i = 1, #self.D do
                self.D[i](self);
            end
            self:originalRemove();
        end

        obj.D = {};
    end

    table.insert(obj.D, func);

end

and you can use this code like this

local group = displsy.newGroup();
local r = display.newRect(group, 0, 0, 300, 300);
AddDestructor(r, function()
    print("Tadaaaa I was called before rect died!");
end);
group:removeSelf();