TodoList.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. onCheck : function (item) {
  14. return item;
  15. },
  16. onUnCheck: function (item) {
  17. return item;
  18. }
  19. };
  20. var Selector = {
  21. data: '[data-widget="todo-list"]'
  22. };
  23. var ClassName = {
  24. done: 'done'
  25. };
  26. // TodoList Class Definition
  27. // =========================
  28. var TodoList = function (element, options) {
  29. this.element = element;
  30. this.options = options;
  31. this._setUpListeners();
  32. };
  33. TodoList.prototype.toggle = function (item) {
  34. item.parents(Selector.li).first().toggleClass(ClassName.done);
  35. if (!item.prop('checked')) {
  36. this.unCheck(item);
  37. return;
  38. }
  39. this.check(item);
  40. };
  41. TodoList.prototype.check = function (item) {
  42. this.options.onCheck.call(item);
  43. };
  44. TodoList.prototype.unCheck = function (item) {
  45. this.options.onUnCheck.call(item);
  46. };
  47. // Private
  48. TodoList.prototype._setUpListeners = function () {
  49. var that = this;
  50. $(this.element).on('change ifChanged', 'input:checkbox', function () {
  51. that.toggle($(this));
  52. });
  53. };
  54. // Plugin Definition
  55. // =================
  56. function Plugin(option) {
  57. return this.each(function () {
  58. var $this = $(this);
  59. var data = $this.data(DataKey);
  60. if (!data) {
  61. var options = $.extend({}, Default, $this.data(), typeof option == 'object' && option);
  62. $this.data(DataKey, (data = new TodoList($this, options)));
  63. }
  64. if (typeof data == 'string') {
  65. if (typeof data[option] == 'undefined') {
  66. throw new Error('No method named ' + option);
  67. }
  68. data[option]();
  69. }
  70. });
  71. }
  72. var old = $.fn.todoList;
  73. $.fn.todoList = Plugin;
  74. $.fn.todoList.Constructor = TodoList;
  75. // No Conflict Mode
  76. // ================
  77. $.fn.todoList.noConflict = function () {
  78. $.fn.todoList = old;
  79. return this;
  80. };
  81. // TodoList Data API
  82. // =================
  83. $(window).on('load', function () {
  84. $(Selector.data).each(function () {
  85. Plugin.call($(this));
  86. });
  87. });
  88. }(jQuery);