PageRenderTime 2396ms CodeModel.GetById 23ms RepoModel.GetById 2ms app.codeStats 0ms

/bwr/components/backbone/examples/todos/todos.js

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