vue 中directive功能的简单实现(2)

3.想办法执行指令的update方法即可,该插件使用了 Object.defineProperty 来定义scope中的每个属性,在其setter中触发指令的update方法。

核心代码

const prefix = 'sd';
const Directives = require('./directives');
const Filters = require('./filters');
// 结果为[sd-text], [sd-class], [sd-on]的字符串
const selector = Object.keys(Directives).map((name) => `[${prefix}-${name}]`).join(',');
const Seed = function(opts) {
 const self = this,
  root = this.el = document.getElementById(opts.id),
  // 筛选出el下所能支持的directive的nodes列表
  els = this.el.querySelectorAll(selector),
  bindings = {};
 this.scope = {};
 // 解析节点
 [].forEach.call(els, processNode);
 // 解析根节点
 processNode(root);
 // 给scope赋值,触发setter方法,此时会调用与其相对应的directive的update方法
 Object.keys(bindings).forEach((key) => {
  this.scope[key] = opts.scope[key];
 });
 function processNode(el) {
  cloneAttributes(el.attributes).forEach((attr) => {
   const directive = parseDirective(attr);
   if (directive) {
    bindDirective(self, el, bindings, directive);
   }
  });
 }
};

可以看到核心方法 processNode 主要做了两件事一个是 parseDirective ,另一个是 bindDirective 。

先来看看 parseDirective 方法:

function parseDirective(attr) {
 if (attr.name.indexOf(prefix) == -1) return;
 // 解析属性名称获取directive
 const noprefix = attr.name.slice(prefix.length + 1),
  argIndex = noprefix.indexOf('-'),
  dirname = argIndex === -1 ? noprefix : noprefix.slice(0, argIndex),
  arg = argIndex === -1 ? null : noprefix.slice(argIndex + 1),
  def = Directives[dirname]
 // 解析属性值获取filters
 const exp = attr.value,
  pipeIndex = exp.indexOf('|'),
  key = (pipeIndex === -1 ? exp : exp.slice(0, pipeIndex)).trim(),
  filters = pipeIndex === -1 ? null : exp.slice(pipeIndex + 1).split('|').map((filterName) => filterName.trim());
 return def ? {
  attr: attr,
  key: key,
  filters: filters,
  argument: arg,
  definition: Directives[dirname],
  update: typeof def === 'function' ? def : def.update
 } : null;
}

以 sd-on-click="toggle | .button" 为例来说明,其中attr对象的name为 sd-on-click ,value为 toggle | .button ,最终解析结果为:

{
 "attr": attr,
 "key": "toggle",
 "filters": [".button"],
 "argument": "click",
 "definition": {"on": {}},
 "update": function(){}
}

紧接着调用 bindDirective 方法

/**
 * 数据绑定
 * @param {Seed} seed  Seed实例对象
 * @param {Element} el  当前node节点
 * @param {Object} bindings 数据绑定存储对象
 * @param {Object} directive 指令解析结果
 */
function bindDirective(seed, el, bindings, directive) {
 // 移除指令属性
 el.removeAttribute(directive.attr.name);
 // 数据属性
 const key = directive.key;
 let binding = bindings[key];
 if (!binding) {
  bindings[key] = binding = {
   value: undefined,
   directives: [] // 与该数据相关的指令
  };
 }
 directive.el = el;
 binding.directives.push(directive);
 if (!seed.scope.hasOwnProperty(key)) {
  bindAccessors(seed, key, binding);
 }
}
/**
 * 重写scope西乡属性的getter和setter
 * @param {Seed} seed Seed实例
 * @param {String} key  对象属性即opts.scope中的属性
 * @param {Object} binding 数据绑定关系对象
 */
function bindAccessors(seed, key, binding) {
 Object.defineProperty(seed.scope, key, {
  get: function() {
   return binding.value;
  },
  set: function(value) {
   binding.value = value;
   // 触发directive
   binding.directives.forEach((directive) => {
    // 如果有过滤器则先执行过滤器
    if (typeof value !== 'undefined' && directive.filters) {
     value = applyFilters(value, directive);
    }
    // 调用update方法
    directive.update(directive.el, value, directive.argument, directive);
   });
  }
 });
}
/**
 * 调用filters依次处理value
 * @param {任意类型} value  数据值
 * @param {Object} directive 解析出来的指令对象
 */
function applyFilters(value, directive) {
 if (directive.definition.customFilter) {
  return directive.definition.customFilter(value, directive.filters);
 } else {
  directive.filters.forEach((name) => {
   if (Filters[name]) {
    value = Filters[name](value);
   }
  });
  return value;
 }
}
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/261.html