vuejs / Discussion

Vue.js discussion
167 stars 17 forks source link

vue 1.0 'attached' hook #60

Open tichris0 opened 10 years ago

tichris0 commented 10 years ago

I was reading the proposed changes for the next version of vue and noticed that the 'attached'/'detached' hooks are due to be removed. I have a couple of use cases right now which rely on this.

Unfortunately in HTML; the only way to get the size of a component is to instantiate it in the DOM and I have components that do pretty fancy layout based on the component's size. Currently I can hook on the 'attached' hooks; do my calculations and update whatever visual that relay on the size.

If it's removed; I'm not sure that I have any other hook/callback where the DOM elements are instantiated where I can do this. Modifying the DOM after it was inserted isn't ideal; but it's my only choice for this.

yyx990803 commented 10 years ago

I see. My reasoning was because these events seemed rarely used but the implementation actually requires quite a bit of overhead to get it working consistently across browsers. But your use case seems legit and I'll try to take another stab at it...

tichris0 commented 10 years ago

Appreciated; Thanks.

holic commented 10 years ago

:+1: I'm doing similar sizing calculations that depend on attached and detached hooks in my viewport-detection plugin: https://github.com/holic/vue-viewport

ayamflow commented 10 years ago

+1 for this! What is the problem with cross browser consistency? DOM manipulations are synchronous so appendChild + execHook('attached') should work everywhere, what am I missing ?

Edit: just saw that a beforeMount hook is planned. Maybe it can replace attached/detached, matched with an afterMount hook ?

yyx990803 commented 10 years ago

@ayamflow the tricky part is a node can be appended to another node which is not in the DOM. Since people are relying on this hook to do dimension calculations, the hook should only be fired when the node is actually inserted into the DOM. It's relatively robust to use MutationEvents/MutationObservers, but it comes at some considerable perf cost when you're not using these hooks, so I'm leaning to implement this by keeping track of instances' in/out DOM states, which is trickier to implement but doesn't impact perf that much.

ayamflow commented 10 years ago

Ah yes, I understand better what nightmare this is :D Yeah keeping track of the $el state in the vm totally makes sense. Really excited to see the first release of vue next!

holic commented 10 years ago

@yyx990803 How about traversing the parentNode until you reach (or don't reach) the document.documentElement? Or perhaps use document.documentElement.contains()?

yyx990803 commented 10 years ago

@holic yes! just did some perf check and document.documentElement.contains() seems performant enough for the use case. Thanks for the suggestion :+1:

pomatechlead commented 8 years ago

Great. Thanks all of them.