top | item 30573278

(no title)

joeyjojo | 4 years ago

How do you manage the lifecycle of objects with the observer pattern? I saw an example of the pattern below that is crucially missing a 'remove' function to unsubscribe from the subject. Like when using events at the app/controller level, I have found a layer/glue starts to form associated with the adding and removing of subscription handlers, and it is this subscription management layer where the majority of complexity and bugs lie. Being inspired by immediate mode renderers, this is what makes React so great - it basically eliminates this entire layer. I might have PTSD working with observers and events from my AS3 days, but if I were building a single page app I wouldn't use the observer pattern over React unless there was a robust way to manage the subscriptions. Perhaps I am overcomplicating something that is actually pretty simple, but I imagine using the observer pattern by itself doesn't really scale beyond the component level?

discuss

order

LAC-Tech|4 years ago

Yeah that's an interesting problem. I mean the simple answer is you just make an unsubscribe method. But that doesn't solve the layer of adding and removing subscription handlers.

mark_and_sweep|4 years ago

Using a subtree, childlist MutationObserver, you can implement a disconnectedCallback for non-custom elements. In the callback, you can clean-up any event handlers that you have added to the element yourself.

naasking|4 years ago

The simple answer from FrTime is to use weak references.