PageRenderTime 68ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/Sample Apps/TodoApp/TodoApp/Scripts/todos.js

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