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, an开发者_运维技巧d 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.
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.
Use FinalizationRegistry
As of August 2020, modern browsers have support for the FinalizationRegistry
method defined by the ECMAScript 2021 (ES12) language specification.
const registry = new FinalizationRegistry((value) => {
console.log(value);
});
const obj = {};
registry.register(obj, "Object 'obj' is garbage collected");
Here we create an instance of FinalizationRegistry
and attached an object to it using .register
. Soon as this object is garbage collected, the callback function passed to the FinalizationRegistry
method is run.
精彩评论