Created
January 21, 2018 15:35
-
-
Save thomas-alrek/d5a4b707d89453e9d71838431b1e9257 to your computer and use it in GitHub Desktop.
Simple ES6 observable/reactive Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const $watchers = Symbol('watchers') | |
| export default class { | |
| constructor (props = {}, handlers = []) { | |
| this[$watchers] = [] | |
| this[Symbol.toStringTag] = this.constructor.name | |
| Object.defineProperty(this, '$watch', { | |
| value (prop, handler) { | |
| if (this[prop]) { | |
| this[$watchers].push({ prop, handler }) | |
| } | |
| }, | |
| writeable: false | |
| }) | |
| const proxy = new Proxy(this, { | |
| get (target, key) { | |
| return target[key] | |
| }, | |
| set (target, key, value) { | |
| if (value !== target[key]) { | |
| target[$watchers] | |
| .filter($watcher => $watcher.prop === key) | |
| .forEach($watcher => $watcher.handler(value, target[key])) | |
| target[key] = value | |
| } | |
| return true | |
| }, | |
| deleteProperty (target, key) { | |
| if (target[key] !== undefined) { | |
| target[$watchers] | |
| .filter($watcher => $watcher.prop === key) | |
| .forEach($watcher => $watcher.handler(undefined, target[key])) | |
| } | |
| delete target[key] | |
| target[$watchers] = target[$watchers] | |
| .filter(($watcher) => $watcher.prop !== key) | |
| } | |
| }) | |
| Object.keys(props).forEach(key => { | |
| proxy[key] = props[key] | |
| }) | |
| return proxy | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment