Skip to content

Instantly share code, notes, and snippets.

@thomas-alrek
Created January 21, 2018 15:35
Show Gist options
  • Select an option

  • Save thomas-alrek/d5a4b707d89453e9d71838431b1e9257 to your computer and use it in GitHub Desktop.

Select an option

Save thomas-alrek/d5a4b707d89453e9d71838431b1e9257 to your computer and use it in GitHub Desktop.
Simple ES6 observable/reactive Object
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