zoukankan      html  css  js  c++  java
  • MVVM数据代理

    MVVM数据代理

    function MVVM(options) {
        this.$options = options || {};
        var data = this._data = this.$options.data;
        var me = this;
    
        // 数据代理
        // 实现 vm.xxx -> vm._data.xxx
        Object.keys(data).forEach(function(key) {
            me._proxyData(key);
        });
    
        this._initComputed();
    
        observe(data, this);
    
        this.$compile = new Compile(options.el || document.body, this)
    }
    
    MVVM.prototype = {
        $watch: function(key, cb, options) {
            new Watcher(this, key, cb);
        },
    
        _proxyData: function(key, setter, getter) {
            var me = this;
            setter = setter || 
            Object.defineProperty(me, key, {
                configurable: false,
                enumerable: true,
                get: function proxyGetter() {
                    return me._data[key];
                },
                set: function proxySetter(newVal) {
                    me._data[key] = newVal;
                }
            });
        },
    
        _initComputed: function() {
            var me = this;
            var computed = this.$options.computed;
            if (typeof computed === 'object') {
                Object.keys(computed).forEach(function(key) {
                    Object.defineProperty(me, key, {
                        get: typeof computed[key] === 'function' 
                                ? computed[key] 
                                : computed[key].get,
                        set: function() {}
                    });
                });
            }
        }
    };
  • 相关阅读:
    快速排序
    Web总结
    浏览器兼容性问题汇总
    AngularJS理论基础
    预处器的对比——Sass、LESS.
    js事件知识整理
    Java script基础
    重拾nodeJs
    全国城市三级联动
    js 获取地址栏参数
  • 原文地址:https://www.cnblogs.com/zzxuan/p/10400355.html
Copyright © 2011-2022 走看看