hopglass/lib/sorttable.js

63 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-04-07 17:41:17 +02:00
define(["virtual-dom"], function (V) {
return function (headings, sortIndex, renderRow) {
var data;
var sortReverse = false;
var el = document.createElement("table");
var elLast = V.h("table");
2015-04-07 17:41:17 +02:00
function sortTable(i) {
sortReverse = i === sortIndex ? !sortReverse : false;
sortIndex = i;
2015-04-07 17:41:17 +02:00
updateView();
2015-04-07 17:41:17 +02:00
}
function sortTableHandler(i) {
return function () {
sortTable(i);
};
2015-04-07 17:41:17 +02:00
}
function updateView() {
var children = [];
2015-04-07 17:41:17 +02:00
if (data.length !== 0) {
var th = headings.map(function (d, i) {
var properties = {
onclick: sortTableHandler(i),
className: "sort-header"
};
2015-04-07 17:41:17 +02:00
if (sortIndex === i) {
properties.className += sortReverse ? " sort-up" : " sort-down";
}
2015-04-07 17:41:17 +02:00
return V.h("th", properties, d.name);
});
2015-04-07 17:41:17 +02:00
var links = data.slice(0).sort(headings[sortIndex].sort);
2015-04-07 17:41:17 +02:00
if (headings[sortIndex].reverse ? !sortReverse : sortReverse) {
links = links.reverse();
}
2015-04-07 17:41:17 +02:00
children.push(V.h("thead", V.h("tr", th)));
children.push(V.h("tbody", links.map(renderRow)));
2015-04-07 17:41:17 +02:00
}
var elNew = V.h("table", children);
el = V.patch(el, V.diff(elLast, elNew));
elLast = elNew;
2015-04-07 17:41:17 +02:00
}
this.setData = function (d) {
data = d;
updateView();
};
2015-04-07 17:41:17 +02:00
this.el = el;
2015-04-07 17:41:17 +02:00
return this;
};
});