Skip to content

Instantly share code, notes, and snippets.

@npras
Created February 20, 2017 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npras/c70c76e3eabb61a8f2b34a6fe585a6da to your computer and use it in GitHub Desktop.
Save npras/c70c76e3eabb61a8f2b34a6fe585a6da to your computer and use it in GitHub Desktop.
VueJS - Implementing Computed Property - Part One
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