Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

剖析一下MVVM原理 #26

Open
wuxianqiang opened this issue Jan 7, 2018 · 0 comments
Open

剖析一下MVVM原理 #26

wuxianqiang opened this issue Jan 7, 2018 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

wuxianqiang commented Jan 7, 2018

什么是MVVM

MVVM叫双向数据绑定,数据影响视图,视图影响数据。

Angular:脏值检测
Vue:数据劫持+发布订阅

实现核心Object.defineProperty

const vue = new Vue({
    el: "#app",
    data: {
        a: {
            a: 1
        }
    }
})
function Vue(options = {}) {
    this.$options = options;
    var data = this._data = this.$options.data;
    observe(data);
    // this代理this._data
    for (const key in data) {
        Object.defineProperty(this, key, {
            enumerable: true,
            get() {
                return this._data[key];
            },
            set(newValue) {
                this._data[key] = newValue;
            }
        })
    }
}

function observe(data) {
    if(Object.prototype.toString.call(data) !== "[object Object]") return;
    return new Observe(data);
}

function Observe(data) {
    for (const key in data) {
        let value = data[key];
        observe(value);
        // 深度响应原理:每次赋予一个新对象的时候都会增加数据劫持
        Object.defineProperty(data, key, {
            enumerable: true,
            get() {
                return value;
            },
            set(newValue) {
                if (newValue === value) return;
                value = newValue;
                observe(newValue);
            }
        })
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant