-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcompile.js
53 lines (45 loc) · 1.27 KB
/
compile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Created by youngwind on 16/8/18.
*/
import Directive from '../directive';
exports._compile = function () {
this._compileNode(this.$el);
};
exports._compileElement = function (node) {
if (node.hasChildNodes()) {
Array.from(node.childNodes).forEach(this._compileNode, this);
}
};
exports._compileText = function (node) {
let patt = /{{\w+}}/g;
let nodeValue = node.nodeValue;
let expressions = nodeValue.match(patt); // 这是一个数组,形如["{{name}}"];
if (!expressions) return;
expressions.forEach((expression) => {
let el = document.createTextNode('');
node.parentNode.insertBefore(el, node);
let property = expression.replace(/[{}]/g, '');
this._bindDirective('text', property, el);
});
node.parentNode.removeChild(node);
};
exports._compileNode = function (node) {
switch (node.nodeType) {
// text
case 1:
this._compileElement(node);
break;
// node
case 3 :
this._compileText(node);
break;
default:
return;
}
};
exports._bindDirective = function (name, expression, node) {
let dirs = this._directives;
dirs.push(
new Directive(name, node, this, expression)
);
};