Created
February 2, 2017 19:45
-
-
Save toddself/93ae0780d5890e7cf55c85cb30154853 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
'use strict' | |
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 | |
} | |
}) | |
} | |
} | |
return base | |
} | |
module.exports = ComputedModel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment