PageRenderTime 74ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/todos/todos.js

https://gitlab.com/kevintcoughlin/backbone
JavaScript | 234 lines | 127 code | 51 blank | 56 comment | 10 complexity | 653e72561b0172e65ae2657a0ef04a95 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. // 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. var TodoList = Backbone.Collection.extend({
  29. // Reference to this collection's model.
  30. model: Todo,
  31. // Save all of the todo items under the `"todos-backbone"` namespace.
  32. localStorage: new Backbone.LocalStorage("todos-backbone"),
  33. // Filter down the list of all todo items that are finished.
  34. done: function() {
  35. return this.where({done: true});
  36. },
  37. // Filter down the list to only todo items that are still not finished.
  38. remaining: function() {
  39. return this.where({done: false});
  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: 'order'
  49. });
  50. // Create our global collection of **Todos**.
  51. var Todos = new TodoList;
  52. // Todo Item View
  53. // --------------
  54. // The DOM element for a todo item...
  55. var TodoView = Backbone.View.extend({
  56. //... is a list tag.
  57. tagName: "li",
  58. // Cache the template function for a single item.
  59. template: _.template($('#item-template').html()),
  60. // The DOM events specific to an item.
  61. events: {
  62. "click .toggle" : "toggleDone",
  63. "dblclick .view" : "edit",
  64. "click a.destroy" : "clear",
  65. "keypress .edit" : "updateOnEnter",
  66. "blur .edit" : "close"
  67. },
  68. // The TodoView listens for changes to its model, re-rendering. Since there's
  69. // a one-to-one correspondence between a **Todo** and a **TodoView** in this
  70. // app, we set a direct reference on the model for convenience.
  71. initialize: function() {
  72. this.listenTo(this.model, 'change', this.render);
  73. this.listenTo(this.model, 'destroy', this.remove);
  74. },
  75. // Re-render the titles of the todo item.
  76. render: function() {
  77. this.$el.html(this.template(this.model.toJSON()));
  78. this.$el.toggleClass('done', this.model.get('done'));
  79. this.input = this.$('.edit');
  80. return this;
  81. },
  82. // Toggle the `"done"` state of the model.
  83. toggleDone: function() {
  84. this.model.toggle();
  85. },
  86. // Switch this view into `"editing"` mode, displaying the input field.
  87. edit: function() {
  88. this.$el.addClass("editing");
  89. this.input.focus();
  90. },
  91. // Close the `"editing"` mode, saving changes to the todo.
  92. close: function() {
  93. var value = this.input.val();
  94. if (!value) {
  95. this.clear();
  96. } else {
  97. this.model.save({title: value});
  98. this.$el.removeClass("editing");
  99. }
  100. },
  101. // If you hit `enter`, we're through editing the item.
  102. updateOnEnter: function(e) {
  103. if (e.keyCode == 13) this.close();
  104. },
  105. // Remove the item, destroy the model.
  106. clear: function() {
  107. this.model.destroy();
  108. }
  109. });
  110. // The Application
  111. // ---------------
  112. // Our overall **AppView** is the top-level piece of UI.
  113. var AppView = Backbone.View.extend({
  114. // Instead of generating a new element, bind to the existing skeleton of
  115. // the App already present in the HTML.
  116. el: $("#todoapp"),
  117. // Our template for the line of statistics at the bottom of the app.
  118. statsTemplate: _.template($('#stats-template').html()),
  119. // Delegated events for creating new items, and clearing completed ones.
  120. events: {
  121. "keypress #new-todo": "createOnEnter",
  122. "click #clear-completed": "clearCompleted",
  123. "click #toggle-all": "toggleAllComplete"
  124. },
  125. // At initialization we bind to the relevant events on the `Todos`
  126. // collection, when items are added or changed. Kick things off by
  127. // loading any preexisting todos that might be saved in *localStorage*.
  128. initialize: function() {
  129. this.input = this.$("#new-todo");
  130. this.allCheckbox = this.$("#toggle-all")[0];
  131. this.listenTo(Todos, 'add', this.addOne);
  132. this.listenTo(Todos, 'reset', this.addAll);
  133. this.listenTo(Todos, 'all', this.render);
  134. this.footer = this.$('footer');
  135. this.main = $('#main');
  136. Todos.fetch();
  137. },
  138. // Re-rendering the App just means refreshing the statistics -- the rest
  139. // of the app doesn't change.
  140. render: function() {
  141. var done = Todos.done().length;
  142. var remaining = Todos.remaining().length;
  143. if (Todos.length) {
  144. this.main.show();
  145. this.footer.show();
  146. this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
  147. } else {
  148. this.main.hide();
  149. this.footer.hide();
  150. }
  151. this.allCheckbox.checked = !remaining;
  152. },
  153. // Add a single todo item to the list by creating a view for it, and
  154. // appending its element to the `<ul>`.
  155. addOne: function(todo) {
  156. var view = new TodoView({model: todo});
  157. this.$("#todo-list").append(view.render().el);
  158. },
  159. // Add all items in the **Todos** collection at once.
  160. addAll: function() {
  161. Todos.each(this.addOne, this);
  162. },
  163. // If you hit return in the main input field, create new **Todo** model,
  164. // persisting it to *localStorage*.
  165. createOnEnter: function(e) {
  166. if (e.keyCode != 13) return;
  167. if (!this.input.val()) return;
  168. Todos.create({title: this.input.val()});
  169. this.input.val('');
  170. },
  171. // Clear all done todo items, destroying their models.
  172. clearCompleted: function() {
  173. _.invoke(Todos.done(), 'destroy');
  174. return false;
  175. },
  176. toggleAllComplete: function () {
  177. var done = this.allCheckbox.checked;
  178. Todos.each(function (todo) { todo.save({'done': done}); });
  179. }
  180. });
  181. // Finally, we kick things off by creating the **App**.
  182. var App = new AppView;
  183. });