Created
November 12, 2018 10:42
-
-
Save shrekuu/4a53b690d797a02fab7a162d81f383b8 to your computer and use it in GitHub Desktop.
an example of object computed property
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
// from: https://codepen.io/lamerumixa/pen/OxZgvO?editors=1010 | |
var Dep = { | |
deps: {}, | |
target: null, | |
subscribe: function (key) { | |
if (!this.deps[key]) this.deps[key] = []; | |
if (this.target && this.deps[key].indexOf(this.target) == -1) { | |
this.deps[key].push(this.target); | |
} | |
}, | |
update: function (key, val) { | |
console.log('update key:', key); | |
console.log('update val:', val); | |
for (var i = 0; i < this.deps[key].length; i++) { | |
this.deps[key][i](); | |
} | |
} | |
} | |
function defineReactive(obj, key, val) { | |
Object.defineProperty(obj, key, { | |
get: function () { | |
Dep.subscribe(key); | |
return val; | |
}, | |
set: function (newValue) { | |
val = newValue; | |
Dep.update(key, val); | |
} | |
}) | |
}; | |
function defineComputed(obj, key, computeFunc, callbackFunc) { | |
getComputed(); | |
Object.defineProperty(obj, key, { | |
get: function () { | |
return getComputed(); | |
}, | |
set: function () { | |
console.warn('nope!'); | |
} | |
}) | |
function getComputed() { | |
Dep.subscribe(key); | |
Dep.target = onDependencyUpdated; | |
var val = computeFunc(); | |
Dep.target = null; | |
return val; | |
} | |
function onDependencyUpdated() { | |
var val = computeFunc(); | |
Dep.update(key, val); | |
callbackFunc(val); | |
} | |
} | |
var person = {}; | |
defineReactive(person, 'age', 16); | |
defineReactive(person, 'country', 'Brazil'); | |
defineComputed(person, 'status', function () { | |
return person.age + ' ' + person.age + ' ' + person.country | |
}, function (newValue) { }); | |
defineComputed(person, 'status2', function () { | |
return person.age + person.age | |
}, function (newValue) { }); | |
person.age = 22; | |
person.country = "Chile"; | |
console.log(Dep) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment