欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue 中directive功能的簡(jiǎn)單實(shí)現(xiàn)

 更新時(shí)間:2018年01月05日 11:55:00   作者:vuestar  
本篇介紹directive的簡(jiǎn)單實(shí)現(xiàn),主要學(xué)習(xí)其實(shí)現(xiàn)的思路及代碼的設(shè)計(jì),需要的朋友參考下吧

2018年首個(gè)計(jì)劃是學(xué)習(xí)vue源碼,查閱了一番資料之后,決定從第一個(gè)commit開(kāi)始看起,這將是一場(chǎng)持久戰(zhàn)!本篇介紹directive的簡(jiǎn)單實(shí)現(xiàn),主要學(xué)習(xí)其實(shí)現(xiàn)的思路及代碼的設(shè)計(jì)(directive和filter擴(kuò)展起來(lái)非常方便,符合設(shè)計(jì)模式中的 開(kāi)閉原則 )。

構(gòu)思API

<div id="app" sd-on-click="toggle | .button">
 <p sd-text="msg | capitalize"></p>
 <p sd-class-red="error" sd-text="content"></p>
 <button class="button">Toggle class</button>
</div>
var app = Seed.create({
 id: 'app',
 scope: {
  msg: 'hello',
  content: 'world',
  error: true,
  toggle: function() {
   app.scope.error = !app.scope.error;
  }
 }
});

實(shí)現(xiàn)功能夠簡(jiǎn)單吧--將scope中的數(shù)據(jù)綁定到app中。

核心邏輯設(shè)計(jì)

指令格式

以 sd-text="msg | capitalize" 為例說(shuō)明:

  1. sd 為統(tǒng)一的前綴標(biāo)識(shí)
  2. text 為指令名稱
  3. capitalize 為過(guò)濾器名稱

其中 | 后面為過(guò)濾器,可以添加多個(gè)。 sd-class-red 中的red為參數(shù)。

代碼結(jié)構(gòu)介紹

main.js 入口文件

// Seed構(gòu)造函數(shù)
const Seed = function(opts) {
};
// 對(duì)外暴露的API
module.exports = {
 create: function(opts) {
  return new Seed(opts);
 }
};
directives.js
module.exports = {
 text: function(el, value) {
  el.textContent = value || '';
 }
};
filters.js
module.exports = {
 capitalize: function(value) {
  value = value.toString();
  return value.charAt(0).toUpperCase() + value.slice(1);
 }
};

就這三個(gè)文件,其中directives和filters都是配置文件,很易于擴(kuò)展。

實(shí)現(xiàn)的大致思路如下:

1.在Seed實(shí)例創(chuàng)建的時(shí)候會(huì)依次解析el容器中node節(jié)點(diǎn)的指令

2.將指令解析結(jié)果封裝為指令對(duì)象,結(jié)構(gòu)為:

屬性 說(shuō)明 類型
attr 原始屬性,如 sd-text String
key 對(duì)應(yīng)scope對(duì)象中的屬性名稱 String
filters 過(guò)濾器名稱列表 Array
definition 該指令的定義,如text對(duì)應(yīng)的函數(shù) Function
argument 從attr中解析出來(lái)的參數(shù)(只支持一個(gè)參數(shù)) String
update 更新directive時(shí)調(diào)用 typeof def === 'function' ? def : def.update Function
bind 如果directive中定義了bind方法,則在 bindDirective 中會(huì)調(diào)用 Function
el 存儲(chǔ)當(dāng)前element元素 Element

3.想辦法執(zhí)行指令的update方法即可,該插件使用了 Object.defineProperty 來(lái)定義scope中的每個(gè)屬性,在其setter中觸發(fā)指令的update方法。

核心代碼

const prefix = 'sd';
const Directives = require('./directives');
const Filters = require('./filters');
// 結(jié)果為[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 = {};
 // 解析節(jié)點(diǎn)
 [].forEach.call(els, processNode);
 // 解析根節(jié)點(diǎn)
 processNode(root);
 // 給scope賦值,觸發(fā)setter方法,此時(shí)會(huì)調(diào)用與其相對(duì)應(yīng)的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 主要做了兩件事一個(gè)是 parseDirective ,另一個(gè)是 bindDirective 。

先來(lái)看看 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" 為例來(lái)說(shuō)明,其中attr對(duì)象的name為 sd-on-click ,value為 toggle | .button ,最終解析結(jié)果為:

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

緊接著調(diào)用 bindDirective 方法

/**
 * 數(shù)據(jù)綁定
 * @param {Seed} seed  Seed實(shí)例對(duì)象
 * @param {Element} el  當(dāng)前node節(jié)點(diǎn)
 * @param {Object} bindings 數(shù)據(jù)綁定存儲(chǔ)對(duì)象
 * @param {Object} directive 指令解析結(jié)果
 */
function bindDirective(seed, el, bindings, directive) {
 // 移除指令屬性
 el.removeAttribute(directive.attr.name);
 // 數(shù)據(jù)屬性
 const key = directive.key;
 let binding = bindings[key];
 if (!binding) {
  bindings[key] = binding = {
   value: undefined,
   directives: [] // 與該數(shù)據(jù)相關(guān)的指令
  };
 }
 directive.el = el;
 binding.directives.push(directive);
 if (!seed.scope.hasOwnProperty(key)) {
  bindAccessors(seed, key, binding);
 }
}
/**
 * 重寫(xiě)scope西鄉(xiāng)屬性的getter和setter
 * @param {Seed} seed Seed實(shí)例
 * @param {String} key  對(duì)象屬性即opts.scope中的屬性
 * @param {Object} binding 數(shù)據(jù)綁定關(guān)系對(duì)象
 */
function bindAccessors(seed, key, binding) {
 Object.defineProperty(seed.scope, key, {
  get: function() {
   return binding.value;
  },
  set: function(value) {
   binding.value = value;
   // 觸發(fā)directive
   binding.directives.forEach((directive) => {
    // 如果有過(guò)濾器則先執(zhí)行過(guò)濾器
    if (typeof value !== 'undefined' && directive.filters) {
     value = applyFilters(value, directive);
    }
    // 調(diào)用update方法
    directive.update(directive.el, value, directive.argument, directive);
   });
  }
 });
}
/**
 * 調(diào)用filters依次處理value
 * @param {任意類型} value  數(shù)據(jù)值
 * @param {Object} directive 解析出來(lái)的指令對(duì)象
 */
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;
 }
}

其中的bindings存放了數(shù)據(jù)和指令的關(guān)系,該對(duì)象中的key為opts.scope中的屬性,value為Object,如下:

{
 "msg": {
 "value": undefined,
 "directives": [] // 上面介紹的directive對(duì)象
 }
}

數(shù)據(jù)與directive建立好關(guān)系之后, bindAccessors 中為seed的scope對(duì)象的屬性重新定義了getter和setter,其中setter會(huì)調(diào)用指令update方法,到此就已經(jīng)完事具備了。

Seed構(gòu)造函數(shù)在實(shí)例化的最后會(huì)迭代bindings中的key,然后從opts.scope找到對(duì)應(yīng)的value, 賦值給了scope對(duì)象,此時(shí)setter中的update就觸發(fā)執(zhí)行了。

下面再看一下 sd-on 指令的定義:

{
 on: {
  update: function(el, handler, event, directive) {
   if (!directive.handlers) {
    directive.handlers = {};
   }
   const handlers = directive.handlers;
   if (handlers[event]) {
    el.removeEventListener(event, handlers[event]);
   }
   if (handler) {
    handler = handler.bind(el);
    el.addEventListener(event, handler);
    handlers[event] = handler;
   }
  },
  customFilter: function(handler, selectors) {
   return function(e) {
    const match = selectors.every((selector) => e.target.matches(selector));
    if (match) {
     handler.apply(this, arguments);
    }
   }
  }
 }
}

發(fā)現(xiàn)它有customFilter,其實(shí)在 applyFilters 中就是針對(duì)該指令做的一個(gè)單獨(dú)的判斷,其中的selectors就是[".button"],最終返回一個(gè)匿名函數(shù)(事件監(jiān)聽(tīng)函數(shù)),該匿名函數(shù)當(dāng)做value傳遞給update方法,被其handler接收,update方法處理的是事件的綁定。這里其實(shí)實(shí)現(xiàn)的是事件的代理功能,customFilter中將handler包裝一層作為事件的監(jiān)聽(tīng)函數(shù),同時(shí)還實(shí)現(xiàn)事件代理功能,設(shè)計(jì)的比較巧妙!

總結(jié)

以上所述是小編給大家介紹的vue 中directive的簡(jiǎn)單實(shí)現(xiàn),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論