Răsfoiți Sursa

Feature/destroy scope (#2733)

* Add failing test

* Make current scope available in destory callback
Simone Todaro 3 ani în urmă
părinte
comite
953d85f110

+ 2 - 2
packages/alpinejs/src/directives/x-data.js

@@ -34,8 +34,8 @@ directive('data', skipDuringClone((el, { expression }, { cleanup }) => {
     reactiveData['init'] && evaluate(el, reactiveData['init'])
     reactiveData['init'] && evaluate(el, reactiveData['init'])
 
 
     cleanup(() => {
     cleanup(() => {
-        undo()
-
         reactiveData['destroy'] && evaluate(el, reactiveData['destroy'])
         reactiveData['destroy'] && evaluate(el, reactiveData['destroy'])
+
+        undo()
     })
     })
 }))
 }))

+ 29 - 1
tests/cypress/integration/custom-data.spec.js

@@ -159,10 +159,38 @@ test('destroy functions inside custom datas are called automatically',
         <div x-data="test">
         <div x-data="test">
             <button x-on:click="test()"></button>
             <button x-on:click="test()"></button>
         </div>
         </div>
-        <span><span>
+        <span></span>
     `,
     `,
     ({ get }) => {
     ({ get }) => {
         get('button').click()
         get('button').click()
         get('span').should(haveText('foo'))
         get('span').should(haveText('foo'))
     }
     }
 )
 )
+
+test('destroy have access to the current scope',
+    html`
+        <script>
+            document.addEventListener('alpine:init', () => {
+                Alpine.data('test', () => ({
+                    destroy() {
+                        document.querySelector('span').textContent = this.foo
+                    },
+                    test() {
+                        Alpine.closestRoot(this.$el).remove()
+                    },
+                    foo: 'bar'
+                }))
+            })
+        </script>
+
+        <div x-data="test">
+            <button x-on:click="test()"></button>
+        </div>
+        <span>baz</span>
+    `,
+    ({ get }) => {
+        get('span').should(haveText('baz'))
+        get('button').click()
+        get('span').should(haveText('bar'))
+    }
+)