Closed chromakode closed 4 years ago
@chromakode 👋 I think a test case would be very useful! I'm a bit confused since handleNodeAdded
happens when a node is added, not removed so it would be great to learn from your example!
Here is a test that deals with this block of code that you could copy -
https://github.com/patrick-steele-idem/morphdom/blob/master/test/browser/test.js#L1040
@chromakode There was in fact a bug! ref #194
Thank you for
morphdom
!I ran into a corner case today in an
onNodeAdded
, in which it can be called with nodes that have been removed from the DOM.When a keyed node is reused and moved to a new parent in a "to" tree,
onNodeAdded
usesreplaceChild
to replace the "to"childNode
node with the existingunmatchedFromEl
node:https://github.com/patrick-steele-idem/morphdom/blob/fe35db9adda1f22fe5856e8e0f78048f8f4b0f18/src/morphdom.js#L156-L164
If I'm understanding correctly, this does two things which surprised me as a user:
handleNodeAdded(curChild)
callsonNodeAdded(curChild)
, which is the node that was removed from the DOM, not the node that ends up in the DOM (unmatchedFromEl
).handleNodeAdded(curChild)
continues traversing the children of the removed "to" node and may trigger additionalonNodeAdded
callbacks for children of the removed node.The documentation of
onNodeAdded
states:I discovered this because I was trying to access the
parentNode
of an node in anonNodeAdded
callback, and was surprised to find itnull
-- I'd assumed all nodesonNodeAdded
would only receive nodes currently in the document. So I think this probably is a bug and merits some change.However, what should the correct behavior be here? In this case, the node was originally in the from tree, so should
morphdom
skip callingonNodeAdded
? Or, because this node (and its children?) were removed/readded to the DOM, shouldonNodeAdded
be called with the "from" node?I'd be happy to add a test and implement the required changes if once it's clear what the correct behavior here should be.