PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/todos-requirejs-1/todos.js

https://github.com/pmichelberger/backbone
JavaScript | 237 lines | 130 code | 48 blank | 59 comment | 11 complexity | 7e7b04334ad76d893061c02fcd47b947 MD5 | raw file
  1. // An example Backbone application contributed by
  2. // [J茅r么me Gravel-Niquet](http://jgn.me/). This demo uses a simple
  3. // [LocalStorage adapter](backbone-localstorage.html)
  4. // to persist Backbone models within your browser.
  5. // Load the application once the DOM is ready, using `jQuery.ready`:
  6. define (function () {
  7. var Todo, TodoList, Todos, TodoView, AppView, module = {};
  8. // Todo Model
  9. // ----------
  10. // Our basic **Todo** model has `text`, `order`, and `done` attributes.
  11. Todo = Backbone.Model.extend({
  12. // Default attributes for a todo item.
  13. defaults: function() {
  14. return {
  15. done: false,
  16. order: Todos.nextOrder()
  17. };
  18. },
  19. // Toggle the `done` state of this todo item.
  20. toggle: function() {
  21. this.save({done: !this.get("done")});
  22. }
  23. });
  24. // Todo Collection
  25. // ---------------
  26. // The collection of todos is backed by *localStorage* instead of a remote
  27. // server.
  28. TodoList = Backbone.Collection.extend({
  29. // Reference to this collection's model.
  30. model: Todo,
  31. // Save all of the todo items under the `"todos"` namespace.
  32. localStorage: new Store("todos"),
  33. // Filter down the list of all todo items that are finished.
  34. done: function() {
  35. return this.filter(function(todo){ return todo.get('done'); });
  36. },
  37. // Filter down the list to only todo items that are still not finished.
  38. remaining: function() {
  39. return this.without.apply(this, this.done());
  40. },
  41. // We keep the Todos in sequential order, despite being saved by unordered
  42. // GUID in the database. This generates the next order number for new items.
  43. nextOrder: function() {
  44. if (!this.length) return 1;
  45. return this.last().get('order') + 1;
  46. },
  47. // Todos are sorted by their original insertion order.
  48. comparator: function(todo) {
  49. return todo.get('order');
  50. }
  51. });
  52. // Create our global collection of **Todos**.
  53. Todos = new TodoList;
  54. // Todo Item View
  55. // --------------
  56. // The DOM element for a todo item...
  57. TodoView = Backbone.View.extend({
  58. //... is a list tag.
  59. tagName: "li",
  60. // Cache the template function for a single item.
  61. template: _.template($('#item-template').html()),
  62. // The DOM events specific to an item.
  63. events: {
  64. "click .check" : "toggleDone",
  65. "dblclick div.todo-text" : "edit",
  66. "click span.todo-destroy" : "clear",
  67. "keypress .todo-input" : "updateOnEnter"
  68. },
  69. // The TodoView listens for changes to its model, re-rendering.
  70. initialize: function() {
  71. this.model.bind('change', this.render, this);
  72. this.model.bind('destroy', this.remove, this);
  73. },
  74. // Re-render the contents of the todo item.
  75. render: function() {
  76. $(this.el).html(this.template(this.model.toJSON()));
  77. this.setText();
  78. return this;
  79. },
  80. // To avoid XSS (not that it would be harmful in this particular app),
  81. // we use `jQuery.text` to set the contents of the todo item.
  82. setText: function() {
  83. var text = this.model.get('text');
  84. this.$('.todo-text').text(text);
  85. this.input = this.$('.todo-input');
  86. this.input.bind('blur', _.bind(this.close, this)).val(text);
  87. },
  88. // Toggle the `"done"` state of the model.
  89. toggleDone: function() {
  90. this.model.toggle();
  91. },
  92. // Switch this view into `"editing"` mode, displaying the input field.
  93. edit: function() {
  94. $(this.el).addClass("editing");
  95. this.input.focus();
  96. },
  97. // Close the `"editing"` mode, saving changes to the todo.
  98. close: function() {
  99. this.model.save({text: this.input.val()});
  100. $(this.el).removeClass("editing");
  101. },
  102. // If you hit `enter`, we're through editing the item.
  103. updateOnEnter: function(e) {
  104. if (e.keyCode == 13) this.close();
  105. },
  106. // Remove this view from the DOM.
  107. remove: function() {
  108. $(this.el).remove();
  109. },
  110. // Remove the item, destroy the model.
  111. clear: function() {
  112. this.model.destroy();
  113. }
  114. });
  115. // The Application
  116. // ---------------
  117. // Our overall **AppView** is the top-level piece of UI.
  118. AppView = Backbone.View.extend({
  119. // Instead of generating a new element, bind to the existing skeleton of
  120. // the App already present in the HTML.
  121. el: $("#todoapp"),
  122. // Our template for the line of statistics at the bottom of the app.
  123. statsTemplate: _.template($('#stats-template').html()),
  124. // Delegated events for creating new items, and clearing completed ones.
  125. events: {
  126. "keypress #new-todo": "createOnEnter",
  127. "keyup #new-todo": "showTooltip",
  128. "click .todo-clear a": "clearCompleted"
  129. },
  130. // At initialization we bind to the relevant events on the `Todos`
  131. // collection, when items are added or changed. Kick things off by
  132. // loading any preexisting todos that might be saved in *localStorage*.
  133. initialize: function() {
  134. this.input = this.$("#new-todo");
  135. Todos.bind('add', this.addOne, this);
  136. Todos.bind('reset', this.addAll, this);
  137. Todos.bind('all', this.render, this);
  138. Todos.fetch();
  139. },
  140. // Re-rendering the App just means refreshing the statistics -- the rest
  141. // of the app doesn't change.
  142. render: function() {
  143. this.$('#todo-stats').html(this.statsTemplate({
  144. total: Todos.length,
  145. done: Todos.done().length,
  146. remaining: Todos.remaining().length
  147. }));
  148. },
  149. // Add a single todo item to the list by creating a view for it, and
  150. // appending its element to the `<ul>`.
  151. addOne: function(todo) {
  152. var view = new TodoView({model: todo});
  153. this.$("#todo-list").append(view.render().el);
  154. },
  155. // Add all items in the **Todos** collection at once.
  156. addAll: function() {
  157. Todos.each(this.addOne);
  158. },
  159. // If you hit return in the main input field, and there is text to save,
  160. // create new **Todo** model persisting it to *localStorage*.
  161. createOnEnter: function(e) {
  162. var text = this.input.val();
  163. if (!text || e.keyCode != 13) return;
  164. Todos.create({text: text});
  165. this.input.val('');
  166. },
  167. // Clear all done todo items, destroying their models.
  168. clearCompleted: function() {
  169. _.each(Todos.done(), function(todo){ todo.destroy(); });
  170. return false;
  171. },
  172. // Lazily show the tooltip that tells you to press `enter` to save
  173. // a new todo item, after one second.
  174. showTooltip: function(e) {
  175. var tooltip = this.$(".ui-tooltip-top");
  176. var val = this.input.val();
  177. tooltip.fadeOut();
  178. if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
  179. if (val == '' || val == this.input.attr('placeholder')) return;
  180. var show = function(){ tooltip.show().fadeIn(); };
  181. this.tooltipTimeout = _.delay(show, 1000);
  182. }
  183. });
  184. // Finally, we kick things off by creating the **App**.
  185. module.init = function () {
  186. return new AppView;
  187. }
  188. return module;
  189. });