PageRenderTime 72ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/option5_php_slim/todos.js

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