walk
噢忘记说了,这里我参考了 Vue 的指令语法,就是在带有冒号 : 的属性名中(当然这里也可所以任何其他你所爱好的符号),可以直接写 JavaScript 的表达式,然后也会供给几个特别的指令,例如 :text, :show 等等来对元素做一些不合的操作。
Directive
其次,再看一下 Directive 内部是若何实现的:
- 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 做了三件事:
- 注册指令(Object.assign(this, directives[this.name]));
- 计算指令表达式的实际值(generate(this.expression)(this.compile.options.data));
- 把计算出来的实际值更新到 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 对 Directive 做了一个异常简单的封装,接收留个必填属性:
- node: 当前所编译的节点,在 Directive 的 update 办法顶用来更新当前节点;
- name: 当前所绑定的指令名称,用来区分具体应用哪个指令更新器来更新视图;
- expression: parse 之后的 JavaScript 的表达式。
推荐阅读
曾经和格力电器董事长董明珠有10亿赌约的小米,要做空调了? 8月10日,小米智能硬件生态链企业智米科技宣布了一款售价4399元的全直流变频空调,但品牌不是“小米&rdqu>>>详细阅读
本文标题:如何实现一个基于DOM的模板引擎
地址:http://www.17bianji.com/lsqh/36664.html
1/2 1

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