首页 > 其他 > 详细

MVVM之观察者Watcher

时间:2020-05-06 18:46:59      阅读:45      评论:0      收藏:0      [点我收藏+]

Watcher

通过新值和老值进行对比 如果发生变化 就调用更新方法
class Watcher {
    constructor(vm, expr, cb) {
        this.vm = vm;
        this.expr = expr;
        this.cb = cb;
        // 获取一下老值
        this.value = this.get();
    }
    getVal(vm, expr) {
        expr = expr.split(‘.‘);
        return expr.reduce((prev, next) => {
            return prev[next];
        }, vm.$data)
    }
    get() {
        Dep.target = this;
        let value = this.getVal(this.vm,this.expr);
        Dep.target = null;
        return value;
    }
    update() {
        // 对外暴露的方法
        let newValue = this.getVal(this.vm,this.expr);
        let oldValue = this.value;
        if(newValue !=oldValue) {
            this.cb(newValue);
        }
    }
}

 

MVVM之观察者Watcher

原文:https://www.cnblogs.com/aisiqi-love/p/12837569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!