watch.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**设置监听器**/
  2. export function setWatcher(page) {
  3. let data = page.data;
  4. let watch = page.watch;
  5. Object.keys(watch).forEach((v) => {
  6. let key = v.split("."); // 将watch中的属性以'.'切分成数组
  7. let nowData = data; // 将data赋值给nowData
  8. for (let i = 0; i < key.length - 1; i++) {
  9. // 遍历key数组的元素,除了最后一个!
  10. nowData = nowData[key[i]]; // 将nowData指向它的key属性对象
  11. }
  12. let lastKey = key[key.length - 1];
  13. // 假设key==='my.name',此时nowData===data['my']===data.my,lastKey==='name'
  14. let watchFun = watch[v].handler || watch[v]; // 兼容带handler和不带handler的两种写法
  15. let deep = watch[v].deep; // 若未设置deep,则为undefine
  16. observe(nowData, lastKey, watchFun, deep, page); // 监听nowData对象的lastKey
  17. });
  18. }
  19. /**监听属性 并执行监听函数**/
  20. function observe(obj, key, watchFun, deep, page) {
  21. var val = obj[key];
  22. // 判断deep是true 且 val不能为空 且 typeof val==='object'(数组内数值变化也需要深度监听)
  23. if (deep && val != null && typeof val === "object") {
  24. Object.keys(val).forEach((childKey) => {
  25. // 遍历val对象下的每一个key
  26. observe(val, childKey, watchFun, deep, page); // 递归调用监听函数
  27. });
  28. }
  29. let that = this;
  30. Object.defineProperty(obj, key, {
  31. configurable: true,
  32. enumerable: true,
  33. set: function (value) {
  34. watchFun.call(page, value, val); // value是新值,val是旧值
  35. val = value;
  36. if (deep) {
  37. // 若是深度监听,重新监听该对象,以便监听其属性。
  38. observe(obj, key, watchFun, deep, page);
  39. }
  40. },
  41. get: function () {
  42. return val;
  43. },
  44. });
  45. }
  46. module.exports = {
  47. setWatcher: setWatcher,
  48. };