作家
登录

如何实现一个基于DOM的模板引擎

作者: 来源: 2017-08-14 09:13:04 阅读 我要评论

 

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 表达式,例如:

  1. // reference: https://github.com/vuejs/vue/blob/dev/src/compiler/parser/text-parser.js#L15-L41 
  2. const tagRE = /\{\{((?:.|\n)+?)\}\}/g; 
  3. function parse(text) { 
  4.     if (!tagRE.test(text)) return JSON.stringify(text); 
  5.  
  6.     const tokens = []; 
  7.     let lastIndex = tagRE.lastIndex = 0; 
  8.     let index, matched; 
  9.  
  10.     while (matched = tagRE.exec(text)) { 
  11.         index = matched.index
  12.         if (index > lastIndex) { 
  13.             tokens.push(JSON.stringify(text.slice(lastIndex, index))); 
  14.         } 
  15.         tokens.push(matched[1].trim()); 
  16.         lastIndex = index + matched[0].length; 
  17.     } 
  18.  
  19.     if (lastIndex < text.length) tokens.push(JSON.stringify(text.slice(lastIndex))); 
  20.  
  21.     return tokens.join('+'); 
  22.  

extract dependency

  1. /** 
  2.  * compile element node 
  3.  * 
  4.  * @param {Node} node 
  5.  */ 
  6. Compile.compile.elementNodes = function (node) { 
  7.     const bindSymbol = `:`; 
  8.     let attributes = [].slice.call(node.attributes), 
  9.         attrName = ``, 
  10.         attrValue = ``, 
  11.         directiveName = ``; 
  12.  
  13.     attributes.map(attribute => { 
  14.         attrName = attribute.name
  15.         attrValue = attribute.value.trim(); 
  16.  

      推荐阅读

      雷军开造空调正面挑战董明珠?小米说只是生态链

    曾经和格力电器董事长董明珠有10亿赌约的小米,要做空调了? 8月10日,小米智能硬件生态链企业智米科技宣布了一款售价4399元的全直流变频空调,但品牌不是&ldquo;小米&rdqu>>>详细阅读


    本文标题:如何实现一个基于DOM的模板引擎

    地址:http://www.17bianji.com/lsqh/36664.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)