作家
登录

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

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

  •             this.compile.textNodes.call(this, node); 
  •         } 
  •         next(); 
  •     }); 
  •  
  •     this.view = template; 
  •     template = null
  •  
  • Compile.compile = {};  
  • walk

    噢忘记说了,这里我参考了 Vue 的指令语法,就是在带有冒号 : 的属性名中(当然这里也可所以任何其他你所爱好的符号),可以直接写 JavaScript 的表达式,然后也会供给几个特别的指令,例如 :text, :show 等等来对元素做一些不合的操作。

    Directive

    其次,再看一下 Directive 内部是若何实现的:

    1. import directives from './directives'
    2. import { generate } from './compile/generate'
    3.  
    4. export default function Directive(options = {}) { 
    5.     Object.assign(this, options); 
    6.     Object.assign(this, directives[this.name]); 
    7.     this.beforeUpdate && this.beforeUpdate(); 
    8.     this.update && this.update(generate(this.expression)(this.compile.options.data)); 
    9.  

    Directive 做了三件事:

    • 注册指令(Object.assign(this, directives[this.name]));
    • 计算指令表达式的实际值(generate(this.expression)(this.compile.options.data));
    • 把计算出来的实际值更新到 DOM 膳绫擎(this.update())。

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

    1. Compile.prototype.bindDirective = function (options) { 
    2.     new Directive({ 
    3.         ...options, 
    4.         compile: this, 
    5.     }); 
    6. }; 
    7.  
    8. Compile.prototype.bindAttribute = function (node, attribute) { 
    9.     if (!hasInterpolation(attribute.value) || attribute.value.trim() == ''return false
    10.  
    11.     this.bindDirective({ 
    12.         node, 
    13.         name'attribute'
    14.         expression: parse.text(attribute.value), 
    15.         attrName: attribute.name
    16.     }); 
    17. };  

    bindDirective 对 Directive 做了一个异常简单的封装,接收留个必填属性:

    关键词: 探索发现

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

    网友点评
    自媒体专栏

    评论

    热度

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