Builds table elements with methods to add rows.
var HtmlTable = new Class({
Implements: [Options, Events, Class.Occlude],
options: {
properties: {
cellpadding: 0,
cellspacing: 0,
border: 0
},
rows: [],
headers: [],
footers: []
},
property: 'HtmlTable',
initialize: function(){
var params = Array.link(arguments, {options: Type.isObject, table: Type.isElement});
this.setOptions(params.options);
this.element = params.table || new Element('table', this.options.properties);
if (this.occlude()) return this.occluded;
this.build();
},
build: function(){
this.element.store('HtmlTable', this);
this.body = document.id(this.element.tBodies[0]) || new Element('tbody').inject(this.element);
$$(this.body.rows);
if (this.options.headers.length) this.setHeaders(this.options.headers);
else this.thead = document.id(this.element.tHead);
if (this.thead) this.head = document.id(this.thead.rows[0]);
if (this.options.footers.length) this.setFooters(this.options.footers);
this.tfoot = document.id(this.element.tFoot);
if (this.tfoot) this.foot = document.id(this.thead.rows[0]);
this.options.rows.each(function(row){
this.push(row);
}, this);
['adopt', 'inject', 'wraps', 'grab', 'replaces', 'dispose'].each(function(method){
this[method] = this.element[method].bind(this.element);
}, this);
},
toElement: function(){
return this.element;
},
empty: function(){
this.body.empty();
return this;
},
set: function(what, items){
var target = (what == 'headers') ? 'tHead' : 'tFoot';
this[target.toLowerCase()] = (document.id(this.element[target]) || new Element(target.toLowerCase()).inject(this.element, 'top')).empty();
var data = this.push(items, {}, this[target.toLowerCase()], what == 'headers' ? 'th' : 'td');
if (what == 'headers') this.head = document.id(this.thead.rows[0]);
else this.foot = document.id(this.thead.rows[0]);
return data;
},
setHeaders: function(headers){
this.set('headers', headers);
return this;
},
setFooters: function(footers){
this.set('footers', footers);
return this;
},
push: function(row, rowProperties, target, tag){
if (typeOf(row) == "element" && row.get('tag') == 'tr'){
row.inject(target || this.body);
return {
tr: row,
tds: row.getChildren('td')
};
}
var tds = row.map(function(data){
var td = new Element(tag || 'td', data ? data.properties : {}),
type = (data ? data.content : '') || data,
element = document.id(type);
if (typeOf(type) != 'string' && element) td.adopt(element);
else td.set('html', type);
return td;
});
return {
tr: new Element('tr', rowProperties).inject(target || this.body).adopt(tds),
tds: tds
};
}
});