浏览代码

Merge pull request #1640 from alpinejs/fix-watch

Only run watcher after specified dependency changes
Caleb Porzio 4 年之前
父节点
当前提交
695047b2f1
共有 2 个文件被更改,包括 25 次插入1 次删除
  1. 5 1
      packages/alpinejs/src/magics/$watch.js
  2. 20 0
      tests/cypress/integration/magics/$watch.spec.js

+ 5 - 1
packages/alpinejs/src/magics/$watch.js

@@ -14,7 +14,11 @@ magic('watch', el => (key, callback) => {
         let div = document.createElement('div')
         div.dataset.throwAway = value
 
-        if (! firstTime) callback(value, oldValue)
+        if (! firstTime) {
+            // We have to queue this watcher as a microtask so that
+            // the watcher doesn't pick up its own dependancies.
+            queueMicrotask(() => callback(value, oldValue))
+        }
 
         oldValue = value
 

+ 20 - 0
tests/cypress/integration/magics/$watch.spec.js

@@ -128,3 +128,23 @@ test('$watch nested arrays',
         get('h2').should(haveText('one,two'))
     }
 )
+
+test('$watch ignores other dependancies',
+    html`
+        <div
+            x-data="{ a: 0, b: 0, c: 0 }"
+            x-init="$watch('a', () => { c = a + b })"
+        >
+            <button @click="a++" id="a">a</button>
+            <button @click="b++" id="b">b</button>
+            <span x-text="c"></span>
+        </div>
+    `,
+    ({ get }) => {
+        get('span').should(haveText('0'))
+        get('#a').click()
+        get('span').should(haveText('1'))
+        get('#b').click()
+        get('span').should(haveText('1'))
+    }
+)