Browse Source

Give a store's "init" function proper reactive context

Caleb Porzio 4 years ago
parent
commit
8b72fe5d06
2 changed files with 27 additions and 3 deletions
  1. 3 3
      packages/alpinejs/src/store.js
  2. 24 0
      tests/cypress/integration/store.spec.js

+ 3 - 3
packages/alpinejs/src/store.js

@@ -10,11 +10,11 @@ export function store(name, value) {
         return stores[name]
     }
 
+    stores[name] = value
+
     if (typeof value === 'object' && value !== null && value.hasOwnProperty('init') && typeof value.init === 'function') {
-        value.init()
+        stores[name].init()
     }
-
-    stores[name] = value
 }
 
 export function getStores() { return stores }

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

@@ -65,3 +65,27 @@ test('can use number as store',
         get('span').should(haveText('1'))
     }
 )
+
+test('store\'s "this" context is reactive for init function',
+    [html`
+        <div x-data>
+        <span x-text="$store.test.count"></span>
+        <button @click="$store.test.increment()" id="button">increment</button>
+        </div>
+    `,
+    `
+        Alpine.store('test', {
+            init() {
+                document.querySelector('#button').addEventListener('click', () => {
+                    this.count++
+                })
+            },
+            count: 0,
+        })
+    `],
+    ({ get }) => {
+        get('span').should(haveText('0'))
+        get('button').click()
+        get('span').should(haveText('1'))
+    }
+)