【vue原始碼】簡單實現directive功能

vuestar發表於2018-01-05

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

構思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中。

核心邏輯設計

指令格式

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

  1. sd為統一的字首標識
  2. text為指令名稱
  3. capitalize為過濾器名稱

其中 | 後面為過濾器,可以新增多個。sd-class-red中的red為引數。

程式碼結構介紹

main.js 入口檔案

// Seed建構函式
const Seed = function(opts) {
    
};

// 對外暴露的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);
    }
};
複製程式碼

就這三個檔案,其中directives和filters都是配置檔案,很易於擴充套件。

實現的大致思路如下:

  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就是在這最初的程式碼逐步成長起來的,如今已然成為一顆參天大樹了。

相關文章