Hello,
In the Custom Attribute section of the documentation, the Aurelia Docs make this statement in the context of memory management:
Weak references: Use WeakMap/WeakSet for object references when appropriate
Could you elaborate a bit as to where, in working with the framework, we should consider this? I’ve never encountered in my Au 1.0 app a situation where I felt WeakMap/WeakSet would solve any problem I was having.
This is just a matter of curiosity. I can’t say I’m having problems at the moment where I think Weak* would be a solution.
The context here is really custom attributes or other low level framework adjacent code where you are holding metadata about objects you do not own. A common example is when a custom attribute wants to associate some state with a DOM element, a view model instance, or another object that is created and destroyed by the framework lifecycle rather than by you directly. If you store that association in a normal Map or on the object itself, you are responsible for cleaning it up perfectly when the element or component is torn down. Miss a path and you have a memory leak.
WeakMap and WeakSet are useful in exactly that scenario. They let you say I want to associate extra data with this object, but I do not want that association to keep the object alive. When the framework drops its last reference to the element or component, the garbage collector is free to reclaim it, and your metadata disappears automatically.
Short version: if you are writing normal components and attributes, ignore it. If you are writing reusable infrastructure that associates state with framework managed objects and you would otherwise need very careful cleanup logic, WeakMap and WeakSet are a nice safety net. Your experience with Au 1 not needing them is totally normal and honestly a good sign that your architecture is clean.
1 Like