瀏覽代碼

feature(watchers): return unwatch method from watch

Ryan Chandler 4 年之前
父節點
當前提交
c43eb708dc
共有 8 個文件被更改,包括 27 次插入2 次删除
  1. 0 0
      dist/spruce.js
  2. 0 0
      dist/spruce.js.map
  3. 0 0
      dist/spruce.module.js
  4. 0 0
      dist/spruce.module.js.map
  5. 0 0
      dist/spruce.umd.js
  6. 0 0
      dist/spruce.umd.js.map
  7. 1 1
      examples/persisted-watchers.html
  8. 26 1
      src/index.js

File diff suppressed because it is too large
+ 0 - 0
dist/spruce.js


File diff suppressed because it is too large
+ 0 - 0
dist/spruce.js.map


File diff suppressed because it is too large
+ 0 - 0
dist/spruce.module.js


File diff suppressed because it is too large
+ 0 - 0
dist/spruce.module.js.map


File diff suppressed because it is too large
+ 0 - 0
dist/spruce.umd.js


File diff suppressed because it is too large
+ 0 - 0
dist/spruce.umd.js.map


+ 1 - 1
examples/persisted-watchers.html

@@ -13,7 +13,7 @@
                 enabled: false,
                 enabled: false,
             }, true);
             }, true);
 
 
-            Spruce.watch('test.enabled', function (enabled) {
+            const [unwatch] = Spruce.watch('test.enabled', function (enabled) {
                 console.log(enabled)
                 console.log(enabled)
             });
             });
         </script>
         </script>

+ 26 - 1
src/index.js

@@ -197,7 +197,7 @@ const Spruce = {
 
 
             this.watchers[name].push(callback)
             this.watchers[name].push(callback)
 
 
-            return
+            return [() => this.unwatch(name, callback)]
         }
         }
 
 
         const nameParts = name.split('.')
         const nameParts = name.split('.')
@@ -228,6 +228,31 @@ const Spruce = {
         }
         }
 
 
         target.__watchers.get(part).add(callback)
         target.__watchers.get(part).add(callback)
+
+        return [() => this.unwatch(name, callback)]
+    },
+
+    unwatch(name, callback) {
+        const nameParts = name.split('.')
+
+        const target = nameParts.reduce((target, part) => {
+            const sub = target[part]
+
+            if (! isNullOrUndefined(sub) && (isObject(sub) || isArray(sub))) {
+                return sub
+            }
+
+            return target
+        }, this.stores)
+
+        const part = Object.is(target, this.get(name)) ? '__self' : nameParts[nameParts.length - 1]
+        const watchers = target.__watchers
+
+        if (! watchers.has(part)) {
+            return
+        }
+
+        watchers.get(part).delete(callback)
     },
     },
 
 
     runWatchers(target, key, value) {
     runWatchers(target, key, value) {

Some files were not shown because too many files changed in this diff