Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
In the micro-channel achieved a small watch program attribute, the attribute data monitor, when the monitored attribute value is changed, we perform the method specified.
watch.js
function observe(obj, key, watchFun, deep, page) {
let val = obj[key];
if (val != null && typeof val === "object" && deep) {
Object.keys(val).forEach((item) => {
observe(val, item, watchFun, deep, page);
});
}
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function(value) {
watchFun.call(page, value, val);
val = value;
if (deep) {
observe(obj, key, watchFun, deep, page);
}
},
get: function() {
return val;
}
});
}
export function setWatcher(page) {
let data = page.data;
let watch = page.watch;
Object.keys(watch).forEach((item) => {
let targetData = data;
let keys = item.split(".");
for (let i = 0; i < keys.length - 1; i++) {
targetData = targetData[keys[i]];
}
let targetKey = keys[keys.length - 1];
let watchFun = watch[item].handler || watch[item];
let deep = watch[item].deep;
observe(targetData, targetKey, watchFun, deep, page);
});
}
Note:
Watch can only monitor existing properties, push (), pop () methods such as array and does not trigger the listener function.
index.js
Test category
//index.js
//获取应用实例
const app = getApp()
import * as watch from "../../utils/watch.js";
Page({
data: {
motto: 'Hello World'
},
onReady: function() {
//启用数据监听
watch.setWatcher(this);
},
watch: {
motto: function(newVal, oldVal) {
console.log(newVal, oldVal);
}
},
ss: function() {
if ('Hello World' == this.data.motto) {
this.setData({
motto: '你好,世界'
})
} else {
this.setData({
motto: 'Hello World'
})
}
}
})
index.wxml
Test page
<text bindtap='ss'>{{motto}}</text>
for reference!
Reference article