使用vue数据辅助器,对于vue或angular等支持双向绑定的数据进行套壳,使ViewModel支持业务逻辑,从而是代码更合理

//一个用于自增的id
let $id = 0;


export default class  {

  bindings = {}

  helperKey = '$'

  helperCoreKey = 'core'

  helperIdKey = 'id'


/*
   增强方法
 
*/
  enh(core, Ht, configs) {

    let key = this.helperKey

    let coreKey = this.helperCoreKey

    let idKey = this.helperIdKey

    if (typeof Ht !== 'function') {
      throw new Error('参数2必须是函数')
    }

    if (typeof core !== 'object') {
      throw new Error('参数1必须是对象')
    }

    let $ = new Ht();

    if (configs) {
      //值复制操作
      for (let i in configs) {
        if (configs.hasOwnProperty(i)) {
          $[i] = configs[i];
        }
      }
    }

    let id ='id'+ ++$id;

    //id 是保留字段
    $[idKey] = id;

    $ = new Proxy($, {
      get(target, p) {
        let r = target[p]
        if (typeof r === 'function') { // 对函数做一层 处理防止其函数的this this指代被篡改
          return () => {
            r.call(target, arguments);
          };
        }
        return r;
      }
    })

    Reflect.defineProperty($, coreKey, {
      configurable: false,
      enumerable: false,
      writable: false,
      value: core
    })

    Reflect.defineProperty(core, key, {
      configurable: false,
      enumerable: false,
      writable: false,
      value: $
    })

    this.bindings[id]=$;

    //新建bindings对象,试
    this.bindings= Object.assign({}, this.bindings);
  }
}

 

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页