Bläddra i källkod

Merge pull request #1166 from stancl/patch-1

Fetch x-init after running onBeforeComponentInitialized
Caleb Porzio 4 år sedan
förälder
incheckning
0f6ebc4f47
2 ändrade filer med 21 tillägg och 1 borttagningar
  1. 2 1
      src/component.js
  2. 19 0
      test/lifecycle.spec.js

+ 2 - 1
src/component.js

@@ -16,7 +16,6 @@ export default class Component {
 
         const dataAttr = this.$el.getAttribute('x-data')
         const dataExpression = dataAttr === '' ? '{}' : dataAttr
-        const initExpression = this.$el.getAttribute('x-init')
 
         let dataExtras = {
             $el: this.$el,
@@ -82,6 +81,8 @@ export default class Component {
         this.showDirectiveLastElement
 
         componentForClone || Alpine.onBeforeComponentInitializeds.forEach(callback => callback(this))
+        
+        const initExpression = this.$el.getAttribute('x-init')
 
         var initReturnedCallback
         // If x-init is present AND we aren't cloning (skip x-init on clone)

+ 19 - 0
test/lifecycle.spec.js

@@ -103,3 +103,22 @@ test('x-init is capable of dispatching an event', async () => {
         expect(document.querySelector('span').textContent).toEqual('baz')
     })
 })
+
+test('onBeforeComponentInitialized is capable of modifying the element', async () => {
+    document.body.innerHTML = `
+        <div x-data="{ init() { window.foo = 'bar' } }"></div>
+    `
+    
+    Alpine.onBeforeComponentInitialized(component => {
+        if (! component.$el.hasAttribute('x-init') && component.$data.init)
+            component.$el.setAttribute('x-init', 'init()')
+    })
+    
+    Alpine.start()
+    
+    await wait(() => {
+        expect(document.querySelector('div').getAttribute('x-init')).toEqual('init()')
+        
+        expect(window.foo).toEqual('bar')
+    })
+})