TodoList.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /**
  2. * --------------------------------------------
  3. * AdminLTE TodoList.js
  4. * License MIT
  5. * --------------------------------------------
  6. */
  7. import $ from 'jquery'
  8. /**
  9. * Constants
  10. * ====================================================
  11. */
  12. const NAME = 'TodoList'
  13. const DATA_KEY = 'lte.todolist'
  14. const JQUERY_NO_CONFLICT = $.fn[NAME]
  15. const SELECTOR_DATA_TOGGLE = '[data-widget="todo-list"]'
  16. const CLASS_NAME_TODO_LIST_DONE = 'done'
  17. const Default = {
  18. onCheck(item) {
  19. return item
  20. },
  21. onUnCheck(item) {
  22. return item
  23. }
  24. }
  25. /**
  26. * Class Definition
  27. * ====================================================
  28. */
  29. class TodoList {
  30. constructor(element, config) {
  31. this._config = config
  32. this._element = element
  33. this._init()
  34. }
  35. // Public
  36. toggle(item) {
  37. item.parents('li').toggleClass(CLASS_NAME_TODO_LIST_DONE)
  38. if (!$(item).prop('checked')) {
  39. this.unCheck(item)
  40. return
  41. }
  42. this.check(item)
  43. }
  44. check(item) {
  45. this._config.onCheck(item)
  46. }
  47. unCheck(item) {
  48. this._config.onUnCheck(item)
  49. }
  50. // Private
  51. _init() {
  52. const $toggleSelector = this._element
  53. $toggleSelector.find('input:checkbox:checked').parents('li').toggleClass(CLASS_NAME_TODO_LIST_DONE)
  54. $toggleSelector.on('change', 'input:checkbox', event => {
  55. this.toggle($(event.target))
  56. })
  57. }
  58. // Static
  59. static _jQueryInterface(config) {
  60. return this.each(function () {
  61. let data = $(this).data(DATA_KEY)
  62. const _config = $.extend({}, Default, typeof config === 'object' ? config : $(this).data())
  63. if (!data) {
  64. data = new TodoList($(this), _config)
  65. $(this).data(DATA_KEY, data)
  66. data._init()
  67. } else if (typeof config === 'string') {
  68. if (typeof data[config] === 'undefined') {
  69. throw new TypeError(`No method named "${config}"`)
  70. }
  71. data[config]()
  72. } else if (typeof config === 'undefined') {
  73. data._init()
  74. }
  75. })
  76. }
  77. }
  78. /**
  79. * Data API
  80. * ====================================================
  81. */
  82. $(window).on('load', () => {
  83. TodoList._jQueryInterface.call($(SELECTOR_DATA_TOGGLE))
  84. })
  85. /**
  86. * jQuery API
  87. * ====================================================
  88. */
  89. $.fn[NAME] = TodoList._jQueryInterface
  90. $.fn[NAME].Constructor = TodoList
  91. $.fn[NAME].noConflict = function () {
  92. $.fn[NAME] = JQUERY_NO_CONFLICT
  93. return TodoList._jQueryInterface
  94. }
  95. export default TodoList