Created
February 20, 2017 12:54
-
-
Save npras/c70c76e3eabb61a8f2b34a6fe585a6da to your computer and use it in GitHub Desktop.
VueJS - Implementing Computed Property - Part One
This file contains hidden or 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 Watcher = require('./watcher'); | |
const noop = function () {}; | |
const sharedPropDef = { | |
enumerable: true, | |
configurable: true, | |
get: noop, | |
set: noop | |
}; | |
function initComputed(vm, computed) { | |
vm._computedWatchers = Object.create(null); | |
for (const key in computed) { | |
value = computed[key]; | |
vm._computedWatchers[key] = new Watcher(vm, value); | |
if (!(key in vm)) { | |
sharedPropDef.set = noop; | |
sharedPropDef.get = function () { | |
const watcher = vm._computedWatchers && vm._computedWatchers[key]; | |
if (watcher) return watcher.value; | |
}; | |
Object.defineProperty(vm, key, sharedPropDef); | |
} // if | |
} // for | |
} | |
////////////////// | |
function myVue(opts) { | |
this._data = opts.data; | |
Object | |
.keys(opts.data) | |
.forEach(key => { | |
sharedPropDef.get = () => this._data[key]; | |
sharedPropDef.set = (val) => { this._data[key] = val; }; | |
Object.defineProperty(this, key, sharedPropDef); | |
}); | |
if (opts.computed) initComputed(this, opts.computed); | |
} | |
////////////////// | |
data = { msg: 'hello' }; | |
computed = { | |
reversedMsg() { | |
console.log('reversed...'); | |
return this.msg.split('').reverse().join(''); | |
}, | |
upperCased() { | |
console.log('uppercased...'); | |
return this.msg.toUpperCase(); | |
} | |
}; | |
opts = { data, computed }; | |
vm = new myVue(opts); | |
console.log(vm.reversedMsg); | |
console.log(vm.reversedMsg); | |
console.log(vm.upperCased); | |
console.log(vm.upperCased); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment