sorttable.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. define(["virtual-dom"], function (V) {
  2. return function(headings, sortIndex, renderRow) {
  3. var data
  4. var sortReverse = false
  5. var el = document.createElement("table")
  6. var elLast = V.h("table")
  7. function sortTable(i) {
  8. sortReverse = i === sortIndex ? !sortReverse : false
  9. sortIndex = i
  10. updateView()
  11. }
  12. function sortTableHandler(i) {
  13. return function () { sortTable(i) }
  14. }
  15. function updateView() {
  16. var children = []
  17. if (data.length !== 0) {
  18. var th = headings.map(function (d, i) {
  19. var properties = { onclick: sortTableHandler(i),
  20. className: "sort-header"
  21. }
  22. if (sortIndex === i)
  23. properties.className += sortReverse ? " sort-up" : " sort-down"
  24. return V.h("th", properties, d.name)
  25. })
  26. var links = data.slice(0).sort(headings[sortIndex].sort)
  27. if (headings[sortIndex].reverse ? !sortReverse : sortReverse)
  28. links = links.reverse()
  29. children.push(V.h("thead", V.h("tr", th)))
  30. children.push(V.h("tbody", links.map(renderRow)))
  31. }
  32. var elNew = V.h("table", children)
  33. el = V.patch(el, V.diff(elLast, elNew))
  34. elLast = elNew
  35. }
  36. this.setData = function (d) {
  37. data = d
  38. updateView()
  39. }
  40. this.el = el
  41. return this
  42. }
  43. })