I'm working on a library that has:
- Some fairly complex cyclical references.
- Registers a variety of event listeners.
- Uses some (singleton-style) objects for global caches
These properties mean that a bunch of stuff in my application are unlikely to be automatically garbage collected.
If the last reference of an object gets garbage collected, I would like to also automatically de-register event handlers, increasing the chances of larger potions of the library can get garbage collected.
In PHP it's possible to use a __destruct
method for this purpose. Is there a similar mechanism possible in Javascript?
Broadly speaking, this would be a fictional example of my dependency graph:
Parent
- childA
- childB
Parent
in this scenario only has outside references, so Javascript can GC this object if it's no longer used, but when this happens, I would like Parent to inform both childA
and childB
that they can de-register their event handlers and do additional cleanup.
Of course I could add a release()
or destroy()
method on the parent, but I would like this to work without requiring the end-user to explicitly signal the parent.