js 实现watch监听数据变化的代码

/**
 * @desc 属性改变监听,属性被set时出发watch的方法,类似vue的watch
 * @constructor
 * @param {object} opts - 构造参数. @default {data:{},watch:{}};
 * @argument {object} data - 要绑定的属性
 * @argument {object} watch - 要监听的属性的回调
 * watch @callback (newVal,oldVal) - 新值与旧值
 */

class watcher {
  constructor(opts) {
    this.$data = this.getBaseType(opts.data) === "Object" ? opts.data : {};
    this.$watch = this.getBaseType(opts.watch) === "Object" ? opts.watch : {};
    for (let key in opts.data) {
      this.setData(key);
    }
  }

  getBaseType(target) {
    const typeStr = Object.prototype.toString.apply(target);
    return typeStr.slice(8, -1);
  }

  setData(_key) {
    Object.defineProperty(this, _key, {
      get: function () {
        console.log(this.$data)
        return this.$data[_key];
      },
      set: function (val) {
        console.log(this.$data)
        const oldVal = this.$data[_key];
        if (oldVal === val) return val;
        this.$data[_key] = val;
        this.$watch[_key] &&
          typeof this.$watch[_key] === "function" &&
          this.$watch[_key].call(this, val, oldVal);
        return val;
      },
    });
  }
}

// export default watcher;

html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>wathc</title>
</head>
<body>
 <script src="./watch.js"></script>
 <script>
  let wm = new watcher({
   data:{
    a: 0,
    b: 'hello'
   },
   watch:{
    a(newVal,oldVal){
     console.log(newVal, oldVal); // 111 0
    }
   }
  })
  wm.a = 111
 </script>
</body>
</html> 
posted @   槑孒  阅读(345)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示