Browse Source

:bug: Fixes reinitializing moved elements (#3995)

Eric Kwoka 1 year ago
parent
commit
e3942876f4
2 changed files with 25 additions and 0 deletions
  1. 1 0
      packages/alpinejs/src/mutation.js
  2. 24 0
      tests/cypress/integration/mutation.spec.js

+ 1 - 0
packages/alpinejs/src/mutation.js

@@ -196,6 +196,7 @@ function onMutate(mutations) {
     for (let node of addedNodes) {
         // If the node was eventually removed as part of one of his
         // parent mutations, skip it
+        if (removedNodes.has(node)) continue
         if (! node.isConnected) continue
 
         delete node._x_ignoreSelf

+ 24 - 0
tests/cypress/integration/mutation.spec.js

@@ -219,3 +219,27 @@ test('no side effects when directives are added to an element that is removed af
         get('span').should(haveText('0'))
     }
 )
+test(
+    "previously initialized elements are not reinitialized on being moved",
+    html`
+        <script>
+            let count = 0;
+            document.addEventListener('alpine:init', () => {
+                Alpine.directive('test', el => {
+                    if (count++ > 3) return;
+                    el.textContent = count;
+                    let wrapper = document.createElement('div');
+                    wrapper.setAttribute('class', 'bg-blue-300 p-8');
+                    el.parentNode.replaceChild(wrapper, el);
+                    wrapper.appendChild(el);
+                });
+            });
+        </script>
+        <div x-data>
+            <div class="bg-red-300 w-32 h-32" x-test></div>
+        </div>
+    `,
+    ({ get }) => {
+        get("[x-test]").should(haveText("1"));
+    }
+);