Re: [whatwg/dom] MutationObserver callbacks happen in wrong order. (Issue #1105)

@annevk seems like a bug in the spec, because browsers behave the same, or browsers decidedly not following the spec in the exact same way.

The examples above clearly show the problem.

@WebReflection 

> the solution is to loop `removedNodes` **before** looping `addedNodes` and everything is fine

That doesn't work when you also need to tell a parent element which child was disconnected as a net result.

If you do the following, synchronously, where all parents are custom elements with MOs.

- remove `a` from parent `A`
- add `a` to parent `B`
- rove `a` from parent `B`
- add `a` to parent `C`

Then the net result is I want to tell `A` that `a` was removed, and tell `C` that I added `a`, but the problem is that the something like following order of MutationObserver reactions can happen:

1. MO for `B` runs, `a` was both added and removed, net result is do nothing
2. MO for `C` runs, Net result is `a` added to `C`, run child connected logic for `C`
3. MO for `A` runs, Net result is `a` removed from `A`, run child disconnected logic for `A`

The error is that 3 needs to run before 2 for the result to be correct.

Now, you mentioned simply running all roved reactions after added actions. How exactly?

I happened to think about this more, and by counting all the addeds and removeds, in then end we are left with either one of these:

- net result is removed from one element, added to another
- net result is added to an element

This is possible to implement by using a counter for each MO on each custom element, then ignoring all net reactions, and finally, always running removeds before addeds like you suggested.

But! This means further code complication, and it will break:

- now suppose we remove the parent elements also, in some arbitrary order,
- and imagine we connect some child elements to them before reconnecting parents to other parents.
- The MOs will have been `disconnected` during that time, and news ones created on reconnect 

This means we must now also run MO-alternative logic in custom element `connectedCallbacks` to handle those cases, and the code will get really ugly, even if we can do it.

---

The main idea here is that, it would be amazing if there were a synchronous element observation API similar to Mutation Events, but without its problems.

I'm really only pointing out above that MOs are extremely over complicated when it comes to observing connected and disconnected children.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1105#issuecomment-1231127985
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/1105/1231127985@github.com>

Received on Tuesday, 30 August 2022 04:32:40 UTC