/**
- 設置監(jiān)聽器
/
export function setWatcher(page) {
let data = page.data;
let watch = page.watch;
Object.keys(watch).forEach(v => {
let key = v.split("."); // 將watch中的屬性以'.'切分成數(shù)組
let nowData = data; // 將data賦值給nowData
for (let i = 0; i < key.length - 1; i++) {
// 遍歷key數(shù)組的元素偶芍,除了最后一個蜈垮!
nowData = nowData[key[i]]; // 將nowData指向它的key屬性對象
}
let lastKey = key[key.length - 1];
// 假設key==='my.name',此時nowData===data['my']===data.my,lastKey==='name'
let watchFun = watch[v].handler || watch[v]; // 兼容帶handler和不帶handler的兩種寫法
let deep = watch[v].deep; // 若未設置deep,則為undefine
observe(nowData, lastKey, watchFun, deep, page); // 監(jiān)聽nowData對象的lastKey
});
}
/* - 監(jiān)聽屬性 并執(zhí)行監(jiān)聽函數(shù)
*/
function observe(obj, key, watchFun, deep, page) {
var val = obj[key];
// 判斷deep是true 且 val不能為空 且 typeof val==='object'(數(shù)組內(nèi)數(shù)值變化也需要深度監(jiān)聽)
if (deep && val != null && typeof val === "object") {
Object.keys(val).forEach(childKey => {
// 遍歷val對象下的每一個key
observe(val, childKey, watchFun, deep, page); // 遞歸調(diào)用監(jiān)聽函數(shù)
});
}
let that = this;
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function(value) {
watchFun.call(page, value, val); // value是新值址晕,val是舊值
val = value;
if (deep) {
// 若是深度監(jiān)聽,重新監(jiān)聽該對象站叼,以便監(jiān)聽其屬性。
observe(obj, key, watchFun, deep, page);
}
},
get: function() {
return val;
}
});
}
module.exports = {
setWatcher: setWatcher
};
-----watch.js------
/**
* 設置監(jiān)聽器
*/
export function setWatcher(page) {
let data = page.data;
let watch = page.watch;
Object.keys(watch).forEach(v => {
let key = v.split("."); // 將watch中的屬性以'.'切分成數(shù)組
let nowData = data; // 將data賦值給nowData
for (let i = 0; i < key.length - 1; i++) {
// 遍歷key數(shù)組的元素震叙,除了最后一個栈雳!
nowData = nowData[key[i]]; // 將nowData指向它的key屬性對象
}
let lastKey = key[key.length - 1];
// 假設key==='my.name',此時nowData===data['my']===data.my,lastKey==='name'
let watchFun = watch[v].handler || watch[v]; // 兼容帶handler和不帶handler的兩種寫法
let deep = watch[v].deep; // 若未設置deep,則為undefine
observe(nowData, lastKey, watchFun, deep, page); // 監(jiān)聽nowData對象的lastKey
});
}
/**
* 監(jiān)聽屬性 并執(zhí)行監(jiān)聽函數(shù)
*/
function observe(obj, key, watchFun, deep, page) {
var val = obj[key];
// 判斷deep是true 且 val不能為空 且 typeof val==='object'(數(shù)組內(nèi)數(shù)值變化也需要深度監(jiān)聽)
if (deep && val != null && typeof val === "object") {
Object.keys(val).forEach(childKey => {
// 遍歷val對象下的每一個key
observe(val, childKey, watchFun, deep, page); // 遞歸調(diào)用監(jiān)聽函數(shù)
});
}
let that = this;
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function(value) {
watchFun.call(page, value, val); // value是新值怯邪,val是舊值
val = value;
if (deep) {
// 若是深度監(jiān)聽,重新監(jiān)聽該對象鸠踪,以便監(jiān)聽其屬性丙者。
observe(obj, key, watchFun, deep, page);
}
},
get: function() {
return val;
}
});
}
module.exports = {
setWatcher: setWatcher
};```