【vue源碼】簡單實現directive功能

2018年首個計劃是學習vue源碼,查閱了一番資料以後,決定從第一個commit開始看起,這將是一場持久戰!本篇介紹directive的簡單實現,主要學習其實現的思路及代碼的設計(directive和filter擴展起來很是方便,符合設計模式中的開閉原則)。javascript

構思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;
        }
    }
});
複製代碼

實現功可以簡單吧--將scope中的數據綁定到app中。html

核心邏輯設計

指令格式

sd-text="msg | capitalize"爲例說明:vue

  1. sd爲統一的前綴標識
  2. text爲指令名稱
  3. capitalize爲過濾器名稱

其中 | 後面爲過濾器,能夠添加多個。sd-class-red中的red爲參數。java

代碼結構介紹

main.js 入口文件node

// Seed構造函數
const Seed = function(opts) {
    
};

// 對外暴露的API
module.exports = {
    create: function(opts) {
        return new Seed(opts);
    }
};
複製代碼

directives.jsjson

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);
    }
};
複製代碼

就這三個文件,其中directives和filters都是配置文件,很易於擴展。api

實現的大體思路以下:app

  1. 在Seed實例建立的時候會依次解析el容器中node節點的指令
  2. 將指令解析結果封裝爲指令對象,結構爲:
屬性 說明 類型
attr 原始屬性,如sd-text String
key 對應scope對象中的屬性名稱 String
filters 過濾器名稱列表 Array
definition 該指令的定義,如text對應的函數 Function
argument 從attr中解析出來的參數(只支持一個參數) String
update 更新directive時調用typeof def === 'function' ? def : def.update Function
bind 若是directive中定義了bind方法,則在bindDirective中會調用 Function
el 存儲當前element元素 Element
  1. 想辦法執行指令的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;
    }
}
複製代碼

其中的bindings存放了數據和指令的關係,該對象中的key爲opts.scope中的屬性,value爲Object,以下:

{
  "msg": {
    "value": undefined,
    "directives": [] // 上面介紹的directive對象
  }
}
複製代碼

數據與directive創建好關係以後,bindAccessors中爲seed的scope對象的屬性從新定義了getter和setter,其中setter會調用指令update方法,到此就已經完事具有了。

Seed構造函數在實例化的最後會迭代bindings中的key,而後從opts.scope找到對應的value,賦值給了scope對象,此時setter中的update就觸發執行了。

下面再看一下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);
              }
          }
      }
  }
}
複製代碼

發現它有customFilter,其實在applyFilters中就是針對該指令作的一個單獨的判斷,其中的selectors就是[".button"],最終返回一個匿名函數(事件監聽函數),該匿名函數當作value傳遞給update方法,被其handler接收,update方法處理的是事件的綁定。這裏其實實現的是事件的代理功能,customFilter中將handler包裝一層做爲事件的監聽函數,同時還實現事件代理功能,設計的比較巧妙!

做者尤小右爲之取名seed寓意深入啊,vue就是在這最初的代碼逐步成長起來的,現在已然成爲一顆參天大樹了。

相關文章
相關標籤/搜索