PageRenderTime 62ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/architecture-examples/backbone/js/todos.js

http://github.com/addyosmani/todomvc
JavaScript | 255 lines | 141 code | 53 blank | 61 comment | 11 complexity | 5652918f69eeff950108174a0e1c5655 MD5 | raw file
Possible License(s): MIT, Apache-2.0, 0BSD, CC-BY-4.0, BSD-3-Clause
  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. $(function(){
  7. // Todo Model
  8. // ----------
  9. // Our basic **Todo** model has `content`, `order`, and `done` attributes.
  10. var Todo = Backbone.Model.extend({
  11. // Default attributes for the todo.
  12. defaults: {
  13. content: "empty todo...",
  14. done: false
  15. },
  16. // Ensure that each todo created has `content`.
  17. initialize: function() {
  18. if (!this.get("content")) {
  19. this.set({"content": this.defaults.content});
  20. }
  21. },
  22. // Toggle the `done` state of this todo item.
  23. toggle: function() {
  24. this.save({done: !this.get("done")});
  25. },
  26. // Remove this Todo from *localStorage* and delete its view.
  27. clear: function() {
  28. this.destroy();
  29. }
  30. });
  31. // Todo Collection
  32. // ---------------
  33. // The collection of todos is backed by *localStorage* instead of a remote
  34. // server.
  35. var TodoList = Backbone.Collection.extend({
  36. // Reference to this collection's model.
  37. model: Todo,
  38. // Save all of the todo items under the `"todos"` namespace.
  39. localStorage: new Store("todos-backbone"),
  40. // Filter down the list of all todo items that are finished.
  41. done: function() {
  42. return this.filter(function(todo){ return todo.get('done'); });
  43. },
  44. // Filter down the list to only todo items that are still not finished.
  45. remaining: function() {
  46. return this.without.apply(this, this.done());
  47. },
  48. // We keep the Todos in sequential order, despite being saved by unordered
  49. // GUID in the database. This generates the next order number for new items.
  50. nextOrder: function() {
  51. if (!this.length) return 1;
  52. return this.last().get('order') + 1;
  53. },
  54. // Todos are sorted by their original insertion order.
  55. comparator: function(todo) {
  56. return todo.get('order');
  57. }
  58. });
  59. // Create our global collection of **Todos**.
  60. var Todos = new TodoList;
  61. // Todo Item View
  62. // --------------
  63. // The DOM element for a todo item...
  64. var TodoView = Backbone.View.extend({
  65. //... is a list tag.
  66. tagName: "li",
  67. // Cache the template function for a single item.
  68. template: _.template($('#item-template').html()),
  69. // The DOM events specific to an item.
  70. events: {
  71. "click .check" : "toggleDone",
  72. "dblclick label.todo-content" : "edit",
  73. "click span.todo-destroy" : "clear",
  74. "keypress .todo-input" : "updateOnEnter",
  75. "blur .todo-input" : "close"
  76. },
  77. // The TodoView listens for changes to its model, re-rendering. Since there's
  78. // a one-to-one correspondence between a **Todo** and a **TodoView** in this
  79. // app, we set a direct reference on the model for convenience.
  80. initialize: function() {
  81. _.bindAll(this, 'render', 'close', 'remove');
  82. this.model.bind('change', this.render);
  83. this.model.bind('destroy', this.remove);
  84. },
  85. // Re-render the contents of the todo item.
  86. render: function() {
  87. $(this.el).html(this.template(this.model.toJSON()));
  88. this.input = this.$('.todo-input');
  89. return this;
  90. },
  91. // Toggle the `"done"` state of the model.
  92. toggleDone: function() {
  93. this.model.toggle();
  94. },
  95. // Switch this view into `"editing"` mode, displaying the input field.
  96. edit: function() {
  97. $(this.el).addClass("editing");
  98. this.input.focus();
  99. },
  100. // Close the `"editing"` mode, saving changes to the todo.
  101. close: function() {
  102. this.model.save({content: this.input.val()});
  103. $(this.el).removeClass("editing");
  104. },
  105. // If you hit `enter`, we're through editing the item.
  106. updateOnEnter: function(e) {
  107. if (e.keyCode == 13) this.close();
  108. },
  109. // Remove the item, destroy the model.
  110. clear: function() {
  111. this.model.clear();
  112. }
  113. });
  114. // The Application
  115. // ---------------
  116. // Our overall **AppView** is the top-level piece of UI.
  117. var AppView = Backbone.View.extend({
  118. // Instead of generating a new element, bind to the existing skeleton of
  119. // the App already present in the HTML.
  120. el: $("#todoapp"),
  121. // Our template for the line of statistics at the bottom of the app.
  122. statsTemplate: _.template($('#stats-template').html()),
  123. // Delegated events for creating new items, and clearing completed ones.
  124. events: {
  125. "keypress #new-todo": "createOnEnter",
  126. "keyup #new-todo": "showTooltip",
  127. "click .todo-clear a": "clearCompleted",
  128. "click .mark-all-done": "toggleAllComplete"
  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. _.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete');
  135. this.input = this.$("#new-todo");
  136. this.allCheckbox = this.$(".mark-all-done")[0];
  137. Todos.bind('add', this.addOne);
  138. Todos.bind('reset', this.addAll);
  139. Todos.bind('all', this.render);
  140. Todos.fetch();
  141. },
  142. // Re-rendering the App just means refreshing the statistics -- the rest
  143. // of the app doesn't change.
  144. render: function() {
  145. var done = Todos.done().length;
  146. var remaining = Todos.remaining().length;
  147. this.$('#todo-stats').html(this.statsTemplate({
  148. total: Todos.length,
  149. done: done,
  150. remaining: remaining
  151. }));
  152. this.allCheckbox.checked = !remaining;
  153. },
  154. // Add a single todo item to the list by creating a view for it, and
  155. // appending its element to the `<ul>`.
  156. addOne: function(todo) {
  157. var view = new TodoView({model: todo});
  158. this.$("#todo-list").append(view.render().el);
  159. },
  160. // Add all items in the **Todos** collection at once.
  161. addAll: function() {
  162. Todos.each(this.addOne);
  163. },
  164. // Generate the attributes for a new Todo item.
  165. newAttributes: function() {
  166. return {
  167. content: this.input.val(),
  168. order: Todos.nextOrder(),
  169. done: false
  170. };
  171. },
  172. // If you hit return in the main input field, create new **Todo** model,
  173. // persisting it to *localStorage*.
  174. createOnEnter: function(e) {
  175. if (e.keyCode != 13) return;
  176. Todos.create(this.newAttributes());
  177. this.input.val('');
  178. },
  179. // Clear all done todo items, destroying their models.
  180. clearCompleted: function() {
  181. _.each(Todos.done(), function(todo){ todo.clear(); });
  182. return false;
  183. },
  184. // Lazily show the tooltip that tells you to press `enter` to save
  185. // a new todo item, after one second.
  186. showTooltip: function(e) {
  187. var tooltip = this.$(".ui-tooltip-top");
  188. var val = this.input.val();
  189. tooltip.fadeOut();
  190. if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
  191. if (val == '' || val == this.input.attr('placeholder')) return;
  192. var show = function(){ tooltip.show().fadeIn(); };
  193. this.tooltipTimeout = _.delay(show, 1000);
  194. },
  195. toggleAllComplete: function () {
  196. var done = this.allCheckbox.checked;
  197. Todos.each(function (todo) { todo.save({'done': done}); });
  198. }
  199. });
  200. // Finally, we kick things off by creating the **App**.
  201. var App = new AppView;
  202. });