当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js 实现watch监听数据变化

js 实现watch监听数据变化

2019年10月13日  | 移动技术网IT编程  | 我要评论

1.js

/**
 * @desc 属性改变监听,属性被set时出发watch的方法,类似vue的watch
 * @author jason 
 * @study https://www.jianshu.com/p/00502d10ea95
 * @data 2018-04-27
 * @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 () {
                return this.$data[_key];
            },
            set : function (val) {
                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;

  2.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>

  3. 给vm.a 从新赋值 就能看到 newval 和oldval的变化

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网