WICG / observable

Observable API proposal
https://wicg.github.io/observable/
Other
543 stars 12 forks source link

When elements are removed from the DOM #118

Closed dariomannu closed 1 week ago

dariomannu commented 4 months ago

I haven't found this explicitly stated, perhaps it was obvious, but I guess when a mounted DOM element with some observable listeners attached gets unmounted, the observable would just complete?

However, elements can also just be detached from the DOM without being actually destroyed and then reattached again, maybe to a different parent node. In that case completing the observable on unmount might not be the best thing to do? Maybe only complete when the node becomes garbage-collectible, as in, removed from the DOM with no reference retained?

domfarolino commented 4 months ago

So we shouldn't think of an element as any special kind of event source, really. The same case is if some object that gets garbage collected holds onto a subscriber and occasionally pushes values to it. Once it's garbage collected, unless it decides to manually complete()/error() the Observable, that Observable will just be quiet from there on out.

I don't think the web platform really has a concept of a destructor that runs at the time of garbage collection, to perform some cleanup work. The closest I could find was FinalizationRegistry, which lets you run a clean-up callback at garbage collection time, but it isn't really used on the platform to register the kind of side effects you mentioned above, like completing an Observable returned by an EventTarget. It also seems like it shouldn't be relied upon: https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob:~:text=The%20timing%20and%20occurrence%20of%20cleanup%20work%20is%20implementation%2Ddefined%20in%20the%20JavaScript%20specification.

So I think the answer is: nothing special would happen.

domfarolino commented 1 week ago

I think my comment above addresses this topic so I will close this issue.