Closed alatielle closed 4 years ago
Keeping track of observed elements seems a bit redundant, as ResizeObserver already does just that? As for an attached method, elements might get a prop with this name in the future, prefixing it like ‘_handleResize’ should help. What other concerns do you have?
Just doesn't feel right to mutate native objects. Feels similar to adding stuff to global / window.
What do you think about dispatching a custom event on the element and adding a listener for it in the hook?
Honestly I'm just not convinced this would worth doing at this point, regardless of the solution. On the whole internet I've only seen that single comment I've linked to that argues it's more performant having a single instance. Non of the more popular measuring libraries utilising ResizeObservers use a single instance either, and I see no issues anywhere related to performance.
Anyway, here are some thoughts:
All in all at the current state I think it's not worth the effort.
Maybe if someone made performance benchmarks where it's clear that this would become a real-life bottleneck I'd consider it, but at the moment it feels like way too much work for way too little.
I thought I solved this for a second.
I could add a callbacks
array, and a single RO that simply calls all callbacks within this array, when changes are detected.
Then all the hook instances need to do is add / remove callbacks as needed.
However within the callback the hooks add, it needs to find the entry that's relevant for the given hook, based on the element observed.
This can be done by using a for loop over the entries array, until target === observed element.
This means that as more hooks (and therefore more observed elements) are added, the entries array might grow in size as well.
☝ This might be something worth looking into though, might not be such a big issue.
Only if a LOT of elements change within the same tick, which would mean that all of these hook-added callbacks would need to loop through the entries array to find only the relevant entry for themselves.
Again, these are the sort of things that really need benchmarking. 😅
I don't think attaching extra props to native objects like an HTMLElement is a good idea. I was thinking more of creating some sort of a registry to keep track of observed elements with a WeakMap or something like that. 🤔