Skip to content

Instantly share code, notes, and snippets.

@toddself
Created February 2, 2017 19:45
Show Gist options
  • Save toddself/93ae0780d5890e7cf55c85cb30154853 to your computer and use it in GitHub Desktop.
Save toddself/93ae0780d5890e7cf55c85cb30154853 to your computer and use it in GitHub Desktop.
'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