Matt-Esch / virtual-dom

A Virtual DOM and diffing algorithm
MIT License
11.67k stars 777 forks source link

Execution of hooks - v0.1.0 #85

Open Matt-Esch opened 10 years ago

Matt-Esch commented 10 years ago

There are outstanding questions that need a solid answer before a v0.1.0 release:

Raynos commented 10 years ago

The hook lifecycle problem

There are multiple problems around them

  1. property order: should hooks get invoked, before properties are set or after properties are set
  2. dom order: should hooks get invoked, before the DOM element is inserted into the DOM or after inserting into the DOM, or when the DOM element is removed from the DOM

In the current implementation (v0.0.12) hooks are:

Raynos commented 10 years ago

Suggestion solutions

There are two ways we can solve this problem.

Picking a fixed time

Let's say we invoke hooks always and try to do it before DOM insertion where possible. Let's also say we invoke hooks before properties are set

Then within a hook you can always add a DOMMutationObserver to get the semantics of "run my code when its added / removed".

Then within a hook you can always add a DOMMutationObserver to wait for the element to be in the DOM and thus get the semantics of "run my code after properties are set"

Supporting lifecycle hints

Let's say we default to invoking hooks when the element is IN the DOM and after properties.

We can then extend the hook interface with:

{
  beforeProperties?: Boolean,
  beforeAppended?: Boolean,
  afterRemoved?: Boolean
}

virtual-dom would read those booleans and if beforeProperties is set it would invoke the hook before properties, instead of afterwards. Note: that invoking the hook before properties is probably means you always want the beforeAppended boolean set to true.

if beforeAppended is set to true it would invoke the hooks before inserting into the DOM, and only invoke the hooks in the before DOM phase, i.e. if the hook is seen in patch() whilst the element is in the DOM we do NOT invoke those hooks.

if afterRemoved is set to true it would invoke the hooks before removing the element from the DOM and only invoke the hooks in the after remove phase. i.e. if the hook is seen in patch() whilst the element is in the DOM we do not invoke those hooks.

Note: we may also want a beforeRemoved boolean.

neonstalwart commented 10 years ago

wouldn't it be more flexible to extend the interface with functions rather than booleans and run the corresponding function at the appropriate time if it exists on the hook? calling different functions would help the hook coordinate running different code at different times and also if you only have booleans then one hook can only participate in one part of the lifecycle.

Gozala commented 9 years ago

I think it would be a lot easier for users if hooks had designated lifecycle methods for each of the execution state.