瀏覽代碼

Merge pull request #1166 from stancl/patch-1

Fetch x-init after running onBeforeComponentInitialized
Caleb Porzio 4 年之前
父節點
當前提交
0f6ebc4f47
共有 2 個文件被更改,包括 21 次插入1 次删除
  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 dataAttr = this.$el.getAttribute('x-data')
         const dataExpression = dataAttr === '' ? '{}' : dataAttr
         const dataExpression = dataAttr === '' ? '{}' : dataAttr
-        const initExpression = this.$el.getAttribute('x-init')
 
 
         let dataExtras = {
         let dataExtras = {
             $el: this.$el,
             $el: this.$el,
@@ -82,6 +81,8 @@ export default class Component {
         this.showDirectiveLastElement
         this.showDirectiveLastElement
 
 
         componentForClone || Alpine.onBeforeComponentInitializeds.forEach(callback => callback(this))
         componentForClone || Alpine.onBeforeComponentInitializeds.forEach(callback => callback(this))
+        
+        const initExpression = this.$el.getAttribute('x-init')
 
 
         var initReturnedCallback
         var initReturnedCallback
         // If x-init is present AND we aren't cloning (skip x-init on clone)
         // 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')
         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')
+    })
+})