Ver código fonte

fix #520 let watchers handle callbacks that trigger removeCb()

Evan You 11 anos atrás
pai
commit
224d67db7c
2 arquivos alterados com 22 adições e 0 exclusões
  1. 7 0
      src/watcher.js
  2. 15 0
      test/unit/specs/watcher_spec.js

+ 7 - 0
src/watcher.js

@@ -151,6 +151,13 @@ p.run = function () {
       var cbs = this.cbs
       for (var i = 0, l = cbs.length; i < l; i++) {
         cbs[i](value, oldValue)
+        // if a callback also removed other callbacks,
+        // we need to adjust the loop accordingly.
+        var removed = l - cbs.length
+        if (removed) {
+          i -= removed
+          l -= removed
+        }
       }
     }
   }

+ 15 - 0
test/unit/specs/watcher_spec.js

@@ -359,4 +359,19 @@ describe('Watcher', function () {
     config.async = true
   })
 
+  it('handle a cb that triggers removeCb', function () {
+    var watcher = new Watcher(vm, 'a', spy)
+    watcher.addCb(function () {
+      watcher.removeCb(spy)
+    })
+    watcher.addCb(function () {})
+    config.async = false
+    expect(function () {
+      vm.a = 2
+    }).not.toThrow()
+    config.async = true
+    expect(spy).toHaveBeenCalled()
+    expect(watcher.cbs.length).toBe(2)
+  })
+
 })