PageRenderTime 24ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/todos/todos.js

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