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

/src/Backbone.Todos/todos.js

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