实现数据改变,视图同步功能

        // 实现数据改变,视图同步功能

        class Dep { // 存储订阅者
            constructor() {}
        }
        class Observer { // 数据代理
            constructor(data) {
                this.analysisData(data);
                this.dep = new Dep();
            }
            analysisData(data) {
                if (Object.prototype.toString.call(data) === '[object Object]') {
                    Object.keys(data).forEach(key => {
                        let value = data[key];
                        this.analysisData(value);
                        let node = undefined;
                        Object.defineProperty(data, key, {
                            enumerable: true,
                            configurable: true,
                            get: () => {
                                if (Dep.node) {
                                    node = Dep.node;
                                }
                                return value
                            },
                            set: (newValue) => {
                                value = newValue;
                                if (node) {
                                    node.textContent = newValue;
                                }
                                return value;
                            }
                        })
                    })
                }
            }
        }
        class Compile { // 数据和dom绑定
            constructor(data, id) {
                this.root = document.querySelector(id);
                this.reg = /\{\{(.*)\}\}/;
                this.data = data;
                this.compile(this.root, this.reg);
            }
            compile(root, reg) {
                let childNodes = root.childNodes;
                [...childNodes].forEach((node) => {
                    let text = node.textContent;
                    if (node.nodeType === 3 && reg.test(text)) {
                        let key = reg.exec(text)[1];
                        Dep.node = node;
                        node.textContent = this.data[key];
                        Dep.node = undefined;
                    }
                    if (node.childNodes && node.childNodes.length > 0) {
                        this.compile(node, reg)
                    }
                })
            }
        }
        class MyVue {
            constructor({
                el,
                data
            }) {
                new Observer(data);
                new Compile(data, el)
            }
        }
        const data = {
            name: '小明'
        };
        new MyVue({
            el: '#root',
            data
        })
        setTimeout(() => {
            data.name = '小红'
        }, 1000)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值