Created
June 7, 2016 16:23
-
-
Save toddself/8ba884f5612bd937aa2c3634301f2d08 to your computer and use it in GitHub Desktop.
This file contains 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 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