PageRenderTime 41ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/todos/todos.js

https://github.com/edmarriner/jQ.Mobi
JavaScript | 238 lines | 131 code | 48 blank | 59 comment | 2 complexity | 504fe96e9bb46b953c7114079a9123f8 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 `text`, `order`, and `done` attributes.
  10. window.Todo = Backbone.Model.extend({
  11. // Default attributes for a todo item.
  12. defaults: function() {
  13. return {
  14. done: false,
  15. order: Todos.nextOrder()
  16. };
  17. },
  18. // Toggle the `done` state of this todo item.
  19. toggle: function() {
  20. this.save({done: !this.get("done")});
  21. }
  22. });
  23. // Todo Collection
  24. // ---------------
  25. // The collection of todos is backed by *localStorage* instead of a remote
  26. // server.
  27. window.TodoList = Backbone.Collection.extend({
  28. // Reference to this collection's model.
  29. model: Todo,
  30. // Save all of the todo items under the `"todos"` namespace.
  31. localStorage: new Store("todos"),
  32. // Filter down the list of all todo items that are finished.
  33. done: function() {
  34. return this.filter(function(todo){ return todo.get('done'); });
  35. },
  36. // Filter down the list to only todo items that are still not finished.
  37. remaining: function() {
  38. return this.without.apply(this, this.done());
  39. },
  40. // We keep the Todos in sequential order, despite being saved by unordered
  41. // GUID in the database. This generates the next order number for new items.
  42. nextOrder: function() {
  43. if (!this.length) return 1;
  44. return this.last().get('order') + 1;
  45. },
  46. // Todos are sorted by their original insertion order.
  47. comparator: function(todo) {
  48. return todo.get('order');
  49. }
  50. });
  51. // Create our global collection of **Todos**.
  52. window.Todos = new TodoList;
  53. // Todo Item View
  54. // --------------
  55. // The DOM element for a todo item...
  56. window.TodoView = Backbone.View.extend({
  57. //... is a list tag.
  58. tagName: "li",
  59. // Cache the template function for a single item.
  60. template: _.template($('#item-template').html()),
  61. // The DOM events specific to an item.
  62. events: {
  63. "click .check" : "toggleDone",
  64. "click div.todo-text" : "edit",
  65. "click span.todo-destroy" : "clear",
  66. "click span.todo-edit" : "updateOnEnter"
  67. },
  68. // The TodoView listens for changes to its model, re-rendering.
  69. initialize: function() {
  70. this.model.bind('change', this.render, this);
  71. this.model.bind('destroy', this.remove, this);
  72. },
  73. // Re-render the contents of the todo item.
  74. render: function() {
  75. $(this.el).html(this.template(this.model.toJSON()));
  76. this.setText();
  77. return this;
  78. },
  79. // To avoid XSS (not that it would be harmful in this particular app),
  80. // we use `jQuery.text` to set the contents of the todo item.
  81. setText: function() {
  82. var text = this.model.get('text');
  83. this.$('.todo-text').text(text);
  84. this.input = this.$('.todo-input');
  85. this.input.bind('blur', _.bind(this.close, this)).val(text);
  86. },
  87. // Toggle the `"done"` state of the model.
  88. toggleDone: function() {
  89. this.model.toggle();
  90. },
  91. // Switch this view into `"editing"` mode, displaying the input field.
  92. edit: function() {
  93. $(this.el).addClass("editing");
  94. this.input.focus();
  95. },
  96. // Close the `"editing"` mode, saving changes to the todo.
  97. close: function() {
  98. this.model.save({text: this.input.val()});
  99. $(this.el).removeClass("editing");
  100. },
  101. // If you hit `enter`, we're through editing the item.
  102. updateOnEnter: function(e) {
  103. this.close();
  104. },
  105. // Remove this view from the DOM.
  106. remove: function() {
  107. $(this.el).remove();
  108. },
  109. // Remove the item, destroy the model.
  110. clear: function() {
  111. this.model.destroy();
  112. }
  113. });
  114. // The Application
  115. // ---------------
  116. // Our overall **AppView** is the top-level piece of UI.
  117. window.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. "click #new-todo-save": "createOnEnter",
  126. "click #new-todo-cancel": "cancelOnPress",
  127. "click #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. $("#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. Todos.create({text: text});
  164. this.input.val('');
  165. this.$(".ui-tooltip-top").fadeOut(300);
  166. },
  167. cancelOnPress:function(e){
  168. this.input.val('');
  169. this.$(".ui-tooltip-top").fadeOut(300);
  170. },
  171. // Clear all done todo items, destroying their models.
  172. clearCompleted: function() {
  173. _.each(Todos.done(), function(todo){ todo.destroy(); });
  174. return false;
  175. },
  176. // Lazily show the tooltip that tells you to press `enter` to save
  177. // a new todo item, after one second.
  178. showTooltip: function(e) {
  179. var tooltip = this.$(".ui-tooltip-top");
  180. var val = this.input.val();
  181. tooltip.fadeOut();
  182. if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
  183. var hide=function(){tooltip.fadeOut('500ms')};
  184. var show = function(){ tooltip.fadeIn('500ms'); _.delay(hide,3000)};
  185. this.tooltipTimeout = _.delay(show, 1000);
  186. }
  187. });
  188. // Finally, we kick things off by creating the **App**.
  189. window.App = new AppView;
  190. });