TodoList.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /* TodoList()
  2. * =========
  3. * Converts a list into a todoList.
  4. *
  5. * @Usage: $('.my-list').todoList(options)
  6. * or add [data-widget="todo-list"] to the ul element
  7. * Pass any option as data-option="value"
  8. */
  9. +function ($) {
  10. 'use strict'
  11. var DataKey = 'lte.todolist'
  12. var Default = {
  13. iCheck : false,
  14. onCheck : function () {
  15. },
  16. onUnCheck: function () {
  17. }
  18. }
  19. var Selector = {
  20. data: '[data-widget="todo-list"]'
  21. }
  22. var ClassName = {
  23. done: 'done'
  24. }
  25. // TodoList Class Definition
  26. // =========================
  27. var TodoList = function (element, options) {
  28. this.element = element
  29. this.options = options
  30. this._setUpListeners()
  31. }
  32. TodoList.prototype.toggle = function (item) {
  33. item.parents(Selector.li).first().toggleClass(ClassName.done)
  34. if (!item.prop('checked')) {
  35. this.unCheck(item)
  36. return
  37. }
  38. this.check(item)
  39. }
  40. TodoList.prototype.check = function (item) {
  41. this.options.onCheck.call(item)
  42. }
  43. TodoList.prototype.unCheck = function (item) {
  44. this.options.onUnCheck.call(item)
  45. }
  46. // Private
  47. TodoList.prototype._setUpListeners = function () {
  48. var that = this
  49. $(this.element).on('change ifChanged', 'input:checkbox', function () {
  50. that.toggle($(this))
  51. })
  52. }
  53. // Plugin Definition
  54. // =================
  55. function Plugin(option) {
  56. return this.each(function () {
  57. var $this = $(this)
  58. var data = $this.data(DataKey)
  59. if (!data) {
  60. var options = $.extend({}, Default, $this.data(), typeof option == 'object' && option)
  61. $this.data(DataKey, (data = new TodoList($this, options)))
  62. }
  63. if (typeof data == 'string') {
  64. if (typeof data[option] == 'undefined') {
  65. throw new Error('No method named ' + option)
  66. }
  67. data[option]()
  68. }
  69. })
  70. }
  71. var old = $.fn.todoList
  72. $.fn.todoList = Plugin
  73. $.fn.todoList.Constructor = TodoList
  74. // No Conflict Mode
  75. // ================
  76. $.fn.todoList.noConflict = function () {
  77. $.fn.todoList = old
  78. return this
  79. }
  80. // TodoList Data API
  81. // =================
  82. $(window).on('load', function () {
  83. $(Selector.data).each(function () {
  84. Plugin.call($(this))
  85. })
  86. })
  87. }(jQuery)