index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. var utils = require('../utils')
  2. module.exports = {
  3. on : require('./on'),
  4. repeat : require('./repeat'),
  5. model : require('./model'),
  6. attr: function (value) {
  7. this.el.setAttribute(this.arg, value)
  8. },
  9. text: function (value) {
  10. this.el.textContent = utils.toText(value)
  11. },
  12. html: function (value) {
  13. this.el.innerHTML = utils.toText(value)
  14. },
  15. style: {
  16. bind: function () {
  17. this.arg = convertCSSProperty(this.arg)
  18. },
  19. update: function (value) {
  20. this.el.style[this.arg] = value
  21. }
  22. },
  23. show: function (value) {
  24. this.el.style.display = value ? '' : 'none'
  25. },
  26. visible: function (value) {
  27. this.el.style.visibility = value ? '' : 'hidden'
  28. },
  29. class: function (value) {
  30. if (this.arg) {
  31. this.el.classList[value ? 'add' : 'remove'](this.arg)
  32. } else {
  33. if (this.lastVal) {
  34. this.el.classList.remove(this.lastVal)
  35. }
  36. this.el.classList.add(value)
  37. this.lastVal = value
  38. }
  39. },
  40. 'if': {
  41. bind: function () {
  42. this.parent = this.el.parentNode
  43. this.ref = document.createComment('sd-if-' + this.key)
  44. },
  45. update: function (value) {
  46. var attached = !!this.el.parentNode
  47. if (!this.parent) { // the node was detached when bound
  48. if (!attached) {
  49. return
  50. } else {
  51. this.parent = this.el.parentNode
  52. }
  53. }
  54. // should always have this.parent if we reach here
  55. if (!value) {
  56. if (attached) {
  57. // insert the reference node
  58. var next = this.el.nextSibling
  59. if (next) {
  60. this.parent.insertBefore(this.ref, next)
  61. } else {
  62. this.parent.appendChild(this.ref)
  63. }
  64. this.parent.removeChild(this.el)
  65. }
  66. } else if (!attached) {
  67. this.parent.insertBefore(this.el, this.ref)
  68. this.parent.removeChild(this.ref)
  69. }
  70. }
  71. }
  72. }
  73. /**
  74. * convert hyphen style CSS property to Camel style
  75. */
  76. var CONVERT_RE = /-(.)/g
  77. function convertCSSProperty (prop) {
  78. if (prop.charAt(0) === '-') prop = prop.slice(1)
  79. return prop.replace(CONVERT_RE, function (m, char) {
  80. return char.toUpperCase()
  81. })
  82. }