-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (90 loc) · 2.48 KB
/
index.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
102
103
104
105
106
107
108
var Emitter = require('emitter')
, domify = require('domify')
module.exports = DataTable;
function DataTable(el,model){
if (!(this instanceof DataTable)) return new DataTable(el,model);
this.el = (typeof el == 'string' ? document.querySelector(el) : el);
this.recordsEl = this.el;
this.headerEl = this.el;
this.model = model;
this.recordViews = [];
return this;
}
Emitter(DataTable.prototype);
DataTable.prototype.record = function(tmpl, viewClass, el){
this._record = tmpl;
this._recordViewClass = viewClass;
if (el)
this.recordsEl = (typeof el == 'string' ? this.el.querySelector(el) : el);
return this;
}
DataTable.prototype.header = function(tmpl, viewClass, el){
this._header = tmpl;
this._headerViewClass = viewClass;
if (el)
this.headerEl = (typeof el == 'string' ? this.el.querySelector(el) : el);
return this;
}
DataTable.prototype.clear = function(){
this.clearHeader();
this.clearRecords();
return this;
}
DataTable.prototype.clearHeader = function(){
empty(this.headerEl);
if (this.headerView) delete this.headerView;
return this;
}
DataTable.prototype.clearRecords = function(){
empty(this.recordsEl);
this.recordViews.splice(0,0);
return this;
}
DataTable.prototype.headerEmpty = function(){
return (!this.headerEl.firstChild);
}
DataTable.prototype.render = function(recs){
if (!this._record) return;
this.clearRecords();
if (this.headerEmpty() && recs.length) this.renderHeader(recs[0]);
for (var i=0;i<recs.length;++i){
var el;
if (this._recordViewClass) {
el = domify(this._record);
var view = new this._recordViewClass(el, recs[i]);
this.recordViews.push(view);
} else {
el = rendered(this._record, recs[i], this.model, i);
}
this.recordsEl.appendChild(el);
}
this.emit('render', recs.length);
}
DataTable.prototype.renderHeader = function(rec){
if (!this._header) return;
this.clearHeader();
var el;
if (this._headerViewClass) {
el = domify(this._header);
var view = new this._headerViewClass(el, this.model, this);
this.headerView = view;
} else {
el = rendered(this._header, rec, this.model);
}
this.headerEl.appendChild(el);
this.emit('render header');
}
// private
function rendered(tmpl,model,modelClass,i){
return domify(
tmpl({ model: modelClass,
index: i,
record: model
})
);
}
/* inlined from yields/empty */
function empty(el,node){
while (node = el.firstChild) el.removeChild(node);
return el;
}