Browse Source

Merge pull request #117 from ryangjchandler/feature/unwatch

feature: unwatch & get watchers
Ryan Chandler 4 years ago
parent
commit
ef1b883b45

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


+ 3 - 1
examples/persisted-watchers.html

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

+ 48 - 1
src/index.js

@@ -197,7 +197,7 @@ const Spruce = {
 
             this.watchers[name].push(callback)
 
-            return
+            return [() => this.unwatch(name, callback)]
         }
 
         const nameParts = name.split('.')
@@ -228,6 +228,53 @@ const Spruce = {
         }
 
         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)
+    },
+
+    watchers(name) {
+        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]
+
+        if (! target.__watchers) {
+            return {}
+        }
+
+        return target.__watchers.get(part)
     },
 
     runWatchers(target, key, value) {

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