PageRenderTime 91ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/todos/todos.js

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