Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement function that fires when JavaScript object is garbage collected?

Actually, garbage collected, destroyed, or otherwise blown out of scope. What I want to do is unbind event handlers on non-DOM elements when an object that has called the bind method is destroyed.


EDIT: I've looked at my code some more, and decided that the only place where I really need this is when the module that contains the object is no longer needed. This is typically when the user loads a new view (it's like "goes to a new page" but in AJAX, right?). So what I did was wrote a simple wrapper method around the bind method, which modifies the callback function to additionally unbind the handler on custom viewchange event. Then I ensure that the viewchange is actually triggered whenever the view is changed.


1 Answers

This isn't possible. There's no way of knowing when something has been or is going to be garbage collected. It's best to ensure you unbind any events before allowing an object to be destroyed.

like image 55
Andy E Avatar answered Oct 21 '25 17:10

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!