generate
讲到这里,其实还有一个异常重要的点没有提到,就是我们若何把 data 真实数据衬着到模板中,比如 <h1>Hey 🌰, {{ greeting }}</h1> 若何衬着成 <h1>Hey 🌰, Hello World</h1>,经由过程下面庞个步调即可计算出表达式的┞锋实数据:
- 把 <h1>Hey 🌰, {{ greeting }}</h1> 解析成 'Hey 🌰, ' + greeting 如许的 JavaScript 表达式;
- 提取个中的依附变量并取得地点 data 中的对应值;
- 应用 new Function() 来创建一个匿名函数来返回这个表达式;
- 最后经由过程调用这个匿名函数来返回最终计算出来的数据并经由过程指令的 update 办法更新到视图中。
parse text
该函数我是直接参考 Vue 的实现,它会把含有双花括号的字符串解析成标准的 JavaScript 表达式,例如:
- // reference: https://github.com/vuejs/vue/blob/dev/src/compiler/parser/text-parser.js#L15-L41
- const tagRE = /\{\{((?:.|\n)+?)\}\}/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('+');
- }
extract dependency
- /**
- * 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();
推荐阅读
曾经和格力电器董事长董明珠有10亿赌约的小米,要做空调了? 8月10日,小米智能硬件生态链企业智米科技宣布了一款售价4399元的全直流变频空调,但品牌不是“小米&rdqu>>>详细阅读
本文标题:如何实现一个基于DOM的模板引擎
地址:http://www.17bianji.com/lsqh/36664.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示