成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

如何實(shí)現(xiàn)一個(gè)基于 DOM 的模板引擎

maxmin / 2797人閱讀

摘要:我們提取變量的目的就是為了在函數(shù)中生成相應(yīng)的變量賦值的字符串便于在函數(shù)中使用,例如這樣的話,只需要在調(diào)用這個(gè)匿名函數(shù)的時(shí)候傳入對(duì)應(yīng)的即可獲得我們想要的結(jié)果了。

題圖:Vincent Guth

注:本文所有代碼均可在本人的個(gè)人項(xiàng)目colon中找到,本文也同步到了知乎專欄

可能你已經(jīng)體會(huì)到了 Vue 所帶來的便捷了,相信有一部分原因也是因?yàn)槠浠?DOM 的語法簡潔的模板渲染引擎。這篇文章將會(huì)介紹如何實(shí)現(xiàn)一個(gè)基于 DOM 的模板引擎(就像 Vue 的模板引擎一樣)。

Preface

開始之前,我們先來看一下最終的效果:

const compiled = Compile(`

Hey ?, {{ greeting }}

`, { greeting: `Hello World`, }); compiled.view // => `

Hey ?, Hello World

`
Compile

實(shí)現(xiàn)一個(gè)模板引擎實(shí)際上就是實(shí)現(xiàn)一個(gè)編譯器,就像這樣:

const compiled = Compile(template: String|Node, data: Object);
compiled.view // => compiled template

首先,讓我們來看下 Compile 內(nèi)部是如何實(shí)現(xiàn)的:

// compile.js
/**
 * template compiler
 *
 * @param {String|Node} template
 * @param {Object} data
 */
function Compile(template, data) {
    if (!(this instanceof Compile)) return new Compile(template, data);

    this.options = {};
    this.data = data;

    if (template instanceof Node) {
        this.options.template = template;
    } else if (typeof template === "string") {
        this.options.template = domify(template);
    } else {
        console.error(`"template" only accept DOM node or string template`);
    }

    template = this.options.template;

    walk(template, (node, next) => {
        if (node.nodeType === 1) {
            // compile element node
            this.compile.elementNodes.call(this, node);
            return next();
        } else if (node.nodeType === 3) {
            // compile text node
            this.compile.textNodes.call(this, node);
        }
        next();
    });

    this.view = template;
    template = null;
}

Compile.compile = {};
walk

通過上面的代碼,可以看到 Compile 的構(gòu)造函數(shù)主要就是做了一件事 ———— 遍歷 template,然后通過判斷節(jié)點(diǎn)類型的不同來做不同的編譯操作,這里就不介紹如何遍歷 template 了,不明白的話可以直接看 walk 函數(shù)的源碼,我們著重來看下如何編譯這些不同類型的節(jié)點(diǎn),以編譯 node.nodeType === 1 的元素節(jié)點(diǎn)為例:

/**
 * compile element node
 *
 * @param {Node} node
 */
Compile.compile.elementNodes = function (node) {
    const bindSymbol = `:`;
    let attributes = [].slice.call(node.attributes),
        attrName = ``,
        attrValue = ``,
        directiveName = ``;

    attributes.map(attribute => {
        attrName = attribute.name;
        attrValue = attribute.value.trim();

        if (attrName.indexOf(bindSymbol) === 0 && attrValue !== "") {
            directiveName = attrName.slice(bindSymbol.length);

            this.bindDirective({
                node,
                expression: attrValue,
                name: directiveName,
            });
            node.removeAttribute(attrName);
        } else {
            this.bindAttribute(node, attribute);
        }
    });
};

噢忘記說了,這里我參考了 Vue 的指令語法,就是在帶有冒號(hào) : 的屬性名中(當(dāng)然這里也可以是任何其他你所喜歡的符號(hào)),可以直接寫 JavaScript 的表達(dá)式,然后也會(huì)提供幾個(gè)特殊的指令,例如 :text, :show 等等來對(duì)元素做一些不同的操作。

其實(shí)該函數(shù)只做了兩件事:

遍歷該節(jié)點(diǎn)的所有屬性,通過判斷屬性類型的不同來做不同的操作,判斷的標(biāo)準(zhǔn)就是屬性名是否是冒號(hào) : 開頭并且屬性的值不為空;

綁定相應(yīng)的指令去更新屬性。

Directive

其次,再看一下 Directive 內(nèi)部是如何實(shí)現(xiàn)的:

import directives from "./directives";
import { generate } from "./compile/generate";

export default function Directive(options = {}) {
    Object.assign(this, options);
    Object.assign(this, directives[this.name]);
    this.beforeUpdate && this.beforeUpdate();
    this.update && this.update(generate(this.expression)(this.compile.options.data));
}

Directive 做了三件事:

注冊(cè)指令(Object.assign(this, directives[this.name]));

計(jì)算指令表達(dá)式的實(shí)際值(generate(this.expression)(this.compile.options.data));

把計(jì)算出來的實(shí)際值更新到 DOM 上面(this.update())。

在介紹指令之前,先看一下它的用法:

Compile.prototype.bindDirective = function (options) {
    new Directive({
        ...options,
        compile: this,
    });
};

Compile.prototype.bindAttribute = function (node, attribute) {
    if (!hasInterpolation(attribute.value) || attribute.value.trim() == "") return false;

    this.bindDirective({
        node,
        name: "attribute",
        expression: parse.text(attribute.value),
        attrName: attribute.name,
    });
};

bindDirective 對(duì) Directive 做了一個(gè)非常簡單的封裝,接受三個(gè)必填屬性:

node: 當(dāng)前所編譯的節(jié)點(diǎn),在 Directiveupdate 方法中用來更新當(dāng)前節(jié)點(diǎn);

name: 當(dāng)前所綁定的指令名稱,用來區(qū)分具體使用哪個(gè)指令更新器來更新視圖;

expression: parse 之后的 JavaScript 的表達(dá)式。

updater

Directive 內(nèi)部我們通過 Object.assign(this, directives[this.name]); 來注冊(cè)不同的指令,所以變量 directives 的值可能是這樣的:

// directives
export default {
    // directive `:show`
    show: {
        beforeUpdate() {},
        update(show) {
            this.node.style.display = show ? `block` : `none`;
        },
    },
    // directive `:text`
    text: {
        beforeUpdate() {},
        update(value) {
            // ...
        },
    },
};

所以假設(shè)某個(gè)指令的名字是 show 的話,那么 Object.assign(this, directives[this.name]); 就等同于:

Object.assign(this, {
    beforeUpdate() {},
    update(show) {
        this.node.style.display = show ? `block` : `none`;
    },
});

表示對(duì)于指令 show,指令更新器會(huì)改變?cè)撛?styledisplay 值,從而實(shí)現(xiàn)對(duì)應(yīng)的功能。所以你會(huì)發(fā)現(xiàn),整個(gè)編譯器結(jié)構(gòu)設(shè)計(jì)好后,如果我們要拓展功能的話,只需簡單地編寫指令的更新器即可,這里再以指令 text 舉個(gè)例子:

// directives
export default {
    // directive `:show`
    // show: { ... },
    // directive `:text`
    text: {
        update(value) {
            this.node.textContent = value;
        },
    },
};

有沒有發(fā)現(xiàn)編寫一個(gè)指令其實(shí)非常的簡單,然后我們就可以這么使用我們的 text 指令了:

const compiled = Compile(`

`, { greeting: `Hello World`, }); compiled.view // => `

Hey ?, Hello World

`
generate

講到這里,其實(shí)還有一個(gè)非常重要的點(diǎn)沒有提到,就是我們?nèi)绾伟?data 真實(shí)數(shù)據(jù)渲染到模板中,比如

Hey ?, {{ greeting }}

如何渲染成

Hey ?, Hello World

,通過下面三個(gè)步驟即可計(jì)算出表達(dá)式的真實(shí)數(shù)據(jù):

Hey ?, {{ greeting }}

解析成 "Hey ?, " + greeting 這樣的 JavaScript 表達(dá)式;

提取其中的依賴變量并取得所在 data 中的對(duì)應(yīng)值;

利用 new Function() 來創(chuàng)建一個(gè)匿名函數(shù)來返回這個(gè)表達(dá)式;

最后通過調(diào)用這個(gè)匿名函數(shù)來返回最終計(jì)算出來的數(shù)據(jù)并通過指令的 update 方法更新到視圖中。

parse text
// reference: https://github.com/vuejs/vue/blob/dev/src/compiler/parser/text-parser.js#L15-L41
const tagRE = /{{((?:.|
)+?)}}/g;
function parse(text) {
    if (!tagRE.test(text)) return JSON.stringify(text);

    const tokens = [];
    let lastIndex = tagRE.lastIndex = 0;
    let index, matched;

    while (matched = tagRE.exec(text)) {
        index = matched.index;
        if (index > lastIndex) {
            tokens.push(JSON.stringify(text.slice(lastIndex, index)));
        }
        tokens.push(matched[1].trim());
        lastIndex = index + matched[0].length;
    }

    if (lastIndex < text.length) tokens.push(JSON.stringify(text.slice(lastIndex)));

    return tokens.join("+");
}

該函數(shù)我是直接參考 Vue 的實(shí)現(xiàn),它會(huì)把含有雙花括號(hào)的字符串解析成標(biāo)準(zhǔn)的 JavaScript 表達(dá)式,例如:

parse(`Hi {{ user.name }}, {{ colon }} is awesome.`);
// => "Hi " + user.name + ", " + colon + " is awesome."
extract dependency

我們會(huì)通過下面這個(gè)函數(shù)來提取出一個(gè)表達(dá)式中可能存在的變量:

const dependencyRE = /"[^"]*"|"[^"]*"|.w*[a-zA-Z$_]w*|w*[a-zA-Z$_]w*:|(w*[a-zA-Z$_]w*)/g;
const globals = [
    "true", "false", "undefined", "null", "NaN", "isNaN", "typeof", "in",
    "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "unescape",
    "escape", "eval", "isFinite", "Number", "String", "parseFloat", "parseInt",
];

function extractDependencies(expression) {
    const dependencies = [];

    expression.replace(dependencyRE, (match, dependency) => {
        if (
            dependency !== undefined &&
            dependencies.indexOf(dependency) === -1 &&
            globals.indexOf(dependency) === -1
        ) {
            dependencies.push(dependency);
        }
    });

    return dependencies;
}

通過正則表達(dá)式 dependencyRE 匹配出可能的變量依賴后,還要進(jìn)行一些對(duì)比,比如是否是全局變量等等。效果如下:

extractDependencies(`typeof String(name) === "string"  && "Hello " + world + "! " + hello.split("").join("") + "."`);
// => ["name", "world", "hello"]

這正是我們需要的結(jié)果,typeof, String, splitjoin 并不是 data 中所依賴的變量,所以不需要被提取出來。

generate
export function generate(expression) {
    const dependencies = extractDependencies(expression);
    let dependenciesCode = "";

    dependencies.map(dependency => dependenciesCode += `var ${dependency} = this.get("${dependency}"); `);

    return new Function(`data`, `${dependenciesCode}return ${expression};`);
}

我們提取變量的目的就是為了在 generate 函數(shù)中生成相應(yīng)的變量賦值的字符串便于在 generate 函數(shù)中使用,例如:

new Function(`data`, `
    var name = data["name"];
    var world = data["world"];
    var hello = data["hello"];
    return typeof String(name) === "string"  && "Hello " + world + "! " + hello.split("").join("") + ".";
`);

// will generated:

function anonymous(data) {
    var name = data["name"];
    var world = data["world"];
    var hello = data["hello"];
    return typeof String(name) === "string"  && "Hello " + world + "! " + hello.split("").join("") + ".";
}

這樣的話,只需要在調(diào)用這個(gè)匿名函數(shù)的時(shí)候傳入對(duì)應(yīng)的 data 即可獲得我們想要的結(jié)果了。現(xiàn)在回過頭來看之前的 Directive 部分代碼應(yīng)該就一目了然了:

export default class Directive {
    constructor(options = {}) {
        // ...
        this.beforeUpdate && this.beforeUpdate();
        this.update && this.update(generate(this.expression)(this.compile.data));
    }
}

generate(this.expression)(this.compile.data) 就是表達(dá)式經(jīng)過 this.compile.data 計(jì)算后我們所需要的值。

compile text node

我們前面只講了如何編譯 node.nodeType === 1 的元素節(jié)點(diǎn),那么文字節(jié)點(diǎn)如何編譯呢,其實(shí)理解了前面所講的內(nèi)容話,文字節(jié)點(diǎn)的編譯就簡單得不能再簡單了:

/**
 * compile text node
 *
 * @param {Node} node
 */
Compile.compile.textNodes = function (node) {
    if (node.textContent.trim() === "") return false;

    this.bindDirective({
        node,
        name: "text",
        expression: parse.text(node.textContent),
    });
};

通過綁定 text 指令,并傳入解析后的 JavaScript 表達(dá)式,在 Directive 內(nèi)部就會(huì)計(jì)算出表達(dá)式實(shí)際的值并調(diào)用 textupdate 函數(shù)更新視圖完成渲染。

:each 指令

到目前為止,該模板引擎只實(shí)現(xiàn)了比較基本的功能,而最常見且重要的列表渲染功能還沒有實(shí)現(xiàn),所以我們現(xiàn)在要實(shí)現(xiàn)一個(gè) :each 指令來渲染一個(gè)列表,這里可能要注意一下,不能按照前面兩個(gè)指令的思路來實(shí)現(xiàn),應(yīng)該換一個(gè)角度來思考,列表渲染其實(shí)相當(dāng)于一個(gè)「子模板」,里面的變量存在于 :each 指令所接收的 data 這個(gè)「局部作用域」中,這么說可能抽象,直接上代碼:

// :each updater
import Compile from "path/to/compile.js";
export default {
    beforeUpdate() {
        this.placeholder = document.createComment(`:each`);
        this.node.parentNode.replaceChild(this.placeholder, this.node);
    },
    update() {
        if (data && !Array.isArray(data)) return;

        const fragment = document.createDocumentFragment();

        data.map((item, index) => {
            const compiled = Compile(this.node.cloneNode(true), { item, index, });
            fragment.appendChild(compiled.view);
        });

        this.placeholder.parentNode.replaceChild(fragment, this.placeholder);
    },
};

update 之前,我們先把 :each 所在節(jié)點(diǎn)從 DOM 結(jié)構(gòu)中去掉,但是要注意的是并不能直接去掉,而是要在去掉的位置插入一個(gè) comment 類型的節(jié)點(diǎn)作為占位符,目的是為了在我們把列表數(shù)據(jù)渲染出來后,能找回原來的位置并把它插入到 DOM 中。

那具體如何編譯這個(gè)所謂的「子模板」呢,首先,我們需要遍歷 :each 指令所接收的 Array 類型的數(shù)據(jù)(目前只支持該類型,當(dāng)然你也可以增加對(duì) Object 類型的支持,原理是一樣的);其次,我們針對(duì)該列表的每一項(xiàng)數(shù)據(jù)進(jìn)行一次模板的編譯并把渲染后的模板插入到創(chuàng)建的 document fragment 中,當(dāng)所有整個(gè)列表編譯完后再把剛剛創(chuàng)建的 comment 類型的占位符替換為 document fragment 以完成列表的渲染。

此時(shí),我們可以這么使用 :each 指令:

Compile(`
  • {{ item.content }}
  • `, { comments: [{ content: `Hello World.`, }, { content: `Just Awesome.`, }, { content: `WOW, Just WOW!`, }], });

    會(huì)渲染成:

  • Hello World.
  • Just Awesome.
  • WOW, Just WOW!
  • 其實(shí)細(xì)心的話你會(huì)發(fā)現(xiàn),模板中使用的 itemindex 變量其實(shí)就是 :each 更新函數(shù)中 Compile(template, data) 編譯器里的 data 值的兩個(gè) key 值。所以要自定義這兩個(gè)變量也是非常簡單的:

    // :each updater
    import Compile from "path/to/compile.js";
    export default {
        beforeUpdate() {
            this.placeholder = document.createComment(`:each`);
            this.node.parentNode.replaceChild(this.placeholder, this.node);
    
            // parse alias
            this.itemName = `item`;
            this.indexName = `index`;
            this.dataName = this.expression;
    
            if (this.expression.indexOf(" in ") != -1) {
                const bracketRE = /(((?:.|
    )+?))/g;
                const [item, data] = this.expression.split(" in ");
                let matched = null;
    
                if (matched = bracketRE.exec(item)) {
                    const [item, index] = matched[1].split(",");
                    index ? this.indexName = index.trim() : "";
                    this.itemName = item.trim();
                } else {
                    this.itemName = item.trim();
                }
    
                this.dataName = data.trim();
            }
    
            this.expression = this.dataName;
        },
        update() {
            if (data && !Array.isArray(data)) return;
    
            const fragment = document.createDocumentFragment();
    
            data.map((item, index) => {
                const compiled = Compile(this.node.cloneNode(true), {
                    [this.itemName]: item,
                    [this.indexName]: index,
                });
                fragment.appendChild(compiled.view);
            });
    
            this.placeholder.parentNode.replaceChild(fragment, this.placeholder);
        },
    };

    這樣一來我們就可以通過 (aliasItem, aliasIndex) in items 來自定義 :each 指令的 itemindex 變量了,原理就是在 beforeUpdate 的時(shí)候去解析 :each 指令的表達(dá)式,提取相關(guān)的變量名,然后上面的例子就可以寫成這樣了:

    Compile(`
  • {{ comment.content }}
  • `, { comments: [{ content: `Hello World.`, }, { content: `Just Awesome.`, }, { content: `WOW, Just WOW!`, }], });
    Conclusion

    到這里,其實(shí)一個(gè)比較簡單的模板引擎算是實(shí)現(xiàn)了,當(dāng)然還有很多地方可以完善的,比如可以增加 :class, :style, :if:src 等等你可以想到的指令功能,添加這些功能都是非常的簡單的。

    全篇介紹下來,整個(gè)核心無非就是遍歷整個(gè)模板的節(jié)點(diǎn)樹,其次針對(duì)每一個(gè)節(jié)點(diǎn)的字符串值來解析成對(duì)應(yīng)的表達(dá)式,然后通過 new Function() 這個(gè)構(gòu)造函數(shù)來計(jì)算成實(shí)際的值,最終通過指令的 update 函數(shù)來更新到視圖上。

    如果還是不清楚這些指令如何編寫的話,可以參考我這個(gè)項(xiàng)目 colon 的相關(guān)源碼(部分代碼可能會(huì)有不影響理解的細(xì)微差別,可忽略),有任何問題都可以在 issue 上提。

    目前有一個(gè)局限就是 DOM-based 的模板引擎只適用于瀏覽器端,目前筆者也正在實(shí)現(xiàn)兼容 Node 端的版本,思路是把字符串模板解析成 AST,然后把更新數(shù)據(jù)到 AST 上,最后再把 AST 轉(zhuǎn)成字符串模板,實(shí)現(xiàn)出來后有空的話再來介紹一下 Node 端的實(shí)現(xiàn)。

    最后,如果上面有說得不對(duì)或者有更好的實(shí)現(xiàn)方式的話,歡迎指出討論。

    文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

    轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/84756.html

    相關(guān)文章

    • Web前端模板引擎の字符串模板

      摘要:這是一個(gè)系列文章,將會(huì)介紹目前前端領(lǐng)域里用到的三種模板引擎技術(shù),它們分別是基于字符串的模板基于操作的模板基于虛擬的模板本文是這個(gè)系列的第一篇,著重介紹基于字符串的模板引擎的實(shí)現(xiàn)原理,分析它的優(yōu)點(diǎn)缺點(diǎn)以及使用的場景。 這是一個(gè)系列文章,將會(huì)介紹目前Web前端領(lǐng)域里用到的三種模板引擎技術(shù),它們分別是: 基于字符串的模板 基于Dom操作的模板 基于虛擬Dom的模板 本文是這個(gè)系列的第一篇...

      Pluser 評(píng)論0 收藏0
    • 構(gòu)建一個(gè)使用 Virtual-DOM 前端模版引擎

      摘要:目錄前言問題的提出模板引擎和結(jié)合的實(shí)現(xiàn)編譯原理相關(guān)模版引擎的詞法分析語法分析與抽象語法樹代碼生成完整的結(jié)語前言本文嘗試構(gòu)建一個(gè)前端模板引擎,并且把這個(gè)引擎和進(jìn)行結(jié)合。于是就構(gòu)思了一個(gè)方案,在前端模板引擎上做手腳。 作者:戴嘉華 轉(zhuǎn)載請(qǐng)注明出處并保留原文鏈接( https://github.com/livoras/blog/issues/14 )和作者信息。 目錄 前言 問題的提出...

      imccl 評(píng)論0 收藏0
    • JavaScript 是如何工作: Shadow DOM 內(nèi)部結(jié)構(gòu)+如何編寫?yīng)毩?em>的組件!

      摘要:向影子樹添加的任何內(nèi)容都將成為宿主元素的本地元素,包括,這就是影子實(shí)現(xiàn)樣式作用域的方式。 這是專門探索 JavaScript 及其所構(gòu)建的組件的系列文章的第 17 篇。 想閱讀更多優(yōu)質(zhì)文章請(qǐng)猛戳GitHub博客,一年百來篇優(yōu)質(zhì)文章等著你! 如果你錯(cuò)過了前面的章節(jié),可以在這里找到它們: JavaScript 是如何工作的:引擎,運(yùn)行時(shí)和調(diào)用堆棧的概述! JavaScript 是如何工作...

      godlong_X 評(píng)論0 收藏0
    • JavaScript 進(jìn)階之深入理解數(shù)據(jù)雙向綁定

      摘要:當(dāng)我們的視圖和數(shù)據(jù)任何一方發(fā)生變化的時(shí)候,我們希望能夠通知對(duì)方也更新,這就是所謂的數(shù)據(jù)雙向綁定。返回值返回傳入函數(shù)的對(duì)象,即第一個(gè)參數(shù)該方法重點(diǎn)是描述,對(duì)象里目前存在的屬性描述符有兩種主要形式數(shù)據(jù)描述符和存取描述符。 前言 談起當(dāng)前前端最熱門的 js 框架,必少不了 Vue、React、Angular,對(duì)于大多數(shù)人來說,我們更多的是在使用框架,對(duì)于框架解決痛點(diǎn)背后使用的基本原理往往關(guān)注...

      sarva 評(píng)論0 收藏0
    • 前端模板原理與實(shí)現(xiàn)

      摘要:套頁面的過程實(shí)際就是將靜態(tài)頁面變成切割成一塊塊,每一塊都是一個(gè),或文件,它們是后端模板引擎的處理對(duì)象其實(shí)模板是不局限于后端還是前端的,模板的本質(zhì)是用于從數(shù)據(jù)變量到實(shí)際的視覺表現(xiàn)代碼這項(xiàng)工作的一種實(shí)現(xiàn)手段。 時(shí)下流行什么react, avalon, angular, vue什么,其核心都離不開前端模板。理解前端模板,是我們了解MV* 的關(guān)鍵。 前端框架最重要的目的是將頁面渲染出來。渲染...

      galois 評(píng)論0 收藏0

    發(fā)表評(píng)論

    0條評(píng)論

    最新活動(dòng)
    閱讀需要支付1元查看
    <