class Observer {
constructor(data) {
this._data = data;
this.walk(this._data);
}
walk(data) {
Object.keys(data).forEach((key) => { this.defineRective(data, key, data[key]) })
};
defineRective(vm, key, value) {
var self = this;
if (value && typeof value === "object") {
this.walk(value);
}
Object.defineProperty(vm, key, {
get: function() {
return value;
},
set: function(newVal) {
if (value != newVal) {
if (newVal && typeof newVal === "object") {
self.walk(newVal);
}
value = newVal;
}
}
})
}
}
module.exports = Observer;
defineRective(vm, key, value) {
// 将这个属性的依赖表达式存储在闭包中。
var dep = new Dep();
var self = this;
if (value && typeof value === "object") {
this.walk(value);
}
Object.defineProperty(vm, key, {
get: function() {
return value;
},
set: function(newVal) {
if (value != newVal) {
if (newVal && typeof newVal === "object") {
self.walk(newVal);
}
value = newVal;
// 通知所有的 viewModel 更新
dep.notify();
}
}
})
}
class Dep {
constructor() {
// 依赖列表
this.dependences = [];
}
// 添加依赖
addDep(watcher) {
if (watcher) {
this.dependences.push(watcher);
}
}
// 通知所有依赖更新
notify() {
this.dependences.forEach((watcher) => {
watcher.update();
})
}
}
module.exports = Dep;
var uid = 0;
class Watcher {
constructor(viewModel, exp, callback) {
this.viewModel = viewModel;
this.id = uid++;
this.exp = exp;
this.callback = callback;
this.oldValue = "";
this.update();
}
get() {
Dep.target = this;
var res = this.compute(this.viewModel, this.exp);
Dep.target = null;
return res;
}
update() {
var newValue = this.get();
if (this.oldValue === newValue) {
return;
}
// callback 里进行Dom 的更新操作
this.callback(newValue, this.oldValue);
this.oldValue = newValue;
}
compute(viewModel, exp) {
var res = replaceWith(viewModel, exp);
return res;
}
}
module.exports = Watcher;
Object.defineProperty(vm, key, {
get: function() {
var watcher = Dep.target;
if (watcher && !dep.dependences[watcher.id]) {
dep.addDep(watcher);
}
return value;
},
set: function(newVal) {
if (value != newVal) {
if (newVal && typeof newVal === "object") {
self.walk(newVal);
}
value = newVal;
dep.notify();
}
}
})
const Observer = require('./Observer.js');
const Watcher = require('./watcher.js');
var data = {
a: 10,
b: {
c: 5,
d: {
e: 20,
}
}
}
var observe = new Observer(data);
var watcher = new Watcher(data, "a+b.c", function(newValue, oldValue) {
console.log("new value is " + newValue);
console.log("oldValue is " + oldValue);
});
console.log("\r\n");
console.log("a has changed to 50,then the expr should has value 55");
data.a = 50;
console.log("\r\n");
console.log("b.c has changed to 50,then the expr should has value 122");
data.b.c = 72;;
console.log("\r\n");
console.log("b.c has reseted an object,then the expr should has value 80");
data.b = { c: 30 }
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有