-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathView.js
101 lines (85 loc) · 2.19 KB
/
View.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class View {
constructor() {
this.template = '';
this.model = {};
this.uiEvents = {};
this.container = $('app');
this.containerHTML = this.container.innerHTML.trim();
_.hide(this.container);
}
setModel(model) {
this.model = model;
}
setTemplate(tpl) {
this.template = tpl;
}
setContainer(container) {
this.container = document.getElementById(container);
}
setEvents(events) {
this.uiEvents = events;
}
getViewData() {
return this.model.export();
}
replaceTpl(html) {
var match = '';
const re = /\{\{\s*([^}]+\S)\s*\}\}/g;
let reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
code = 'var r=[];\n',
cursor = 0;
var add = function(line, js) {
js
? code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n'
: code += line != ''
? 'r.push("' + line.replace(/"/g, '\\"') + '");\n'
: '';
return add;
};
while (match = re.exec(html)) {
add(html.slice(cursor, match.index))('this.' + match[1], true);
cursor = match.index + match[0].length;
}
add(html.substr(cursor, html.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[\r\t\n]/g, '')).apply(this.model.store);
}
checkContainer() {
let tpl = this.containerHTML;
tpl = this.replaceTpl(tpl);
return tpl;
}
renderContainer() {
let tpl = this.checkContainer();
this.container.innerHTML = tpl;
_.show(this.container);
this.bindEvents();
}
renderTemplate(target) {
target.innerHTML = replaceTpl(this.template);
}
renderBody() {
let tpl = document.body.innerHTML;
this.replaceTpl(tpl);
}
addEvent(target, event, handler) {
target.addEventListener(event, handler, false);
}
removeEvent() {
target.removeEventListener(event, handler, false);
}
bindEvents() {
for (let key in this.events) {
if (this.events.hasOwnProperty(key)) {
let arr = key.split('|');
addEvent($(arr[0]), arr[1], this.events[key]);
}
}
}
destory() {
this.container && (this.container.innerHTML = '');
}
}
function $(id) {
return document.getElementById(id);
}