Skip to content

Instantly share code, notes, and snippets.

@toddself
Created June 7, 2016 16:23
Show Gist options
  • Save toddself/8ba884f5612bd937aa2c3634301f2d08 to your computer and use it in GitHub Desktop.
Save toddself/8ba884f5612bd937aa2c3634301f2d08 to your computer and use it in GitHub Desktop.
const EventEmitter = require('events')
function ComputedModel (props) {
const base = Object.create(new EventEmitter())
const keys = Object.keys(props)
for (let i = 0, len = keys.length; i < len; i++) {
const key = keys[i]
const prop = props[key]
Object.defineProperty(base, `_${key}`, {writable: true, value: prop})
if (typeof prop === 'function') {
Object.defineProperty(base, key, {
get: function () {
return this[`_${key}`]()
}
})
} else {
Object.defineProperty(base, key, {
enumerable: true,
get: function () {
return this[`_${key}`]
},
set: function (val) {
this[`_${key}`] = val
this.emit('set', {key: key, value: val})
}
})
}
}
return base
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment