PageRenderTime 3392ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/M5/todos.js

https://github.com/borismus/DevTools-Lab
JavaScript | 305 lines | 175 code | 57 blank | 73 comment | 19 complexity | dabc1103fdfa06388bef7be6b1dc03f8 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. // If you don't provide a todo, one will be provided for you.
  12. EMPTY: "empty todo...",
  13. // Ensure that each todo created has `content`.
  14. initialize: function() {
  15. if (!this.get("content")) {
  16. this.set({"content": this.EMPTY});
  17. }
  18. },
  19. countSheep: function() {
  20. var start = new Date();
  21. while (true) {
  22. var now = new Date();
  23. if (now - start > 500) {
  24. return;
  25. }
  26. }
  27. },
  28. // Toggle the `done` state of this todo item.
  29. toggle: function() {
  30. //this.countSheep();
  31. this.save({done: !this.get("done")});
  32. if (Todos.remaining().length == 0){
  33. window.console && console.log('woohoo! you finished all your items! highfive! _o/\o_');
  34. }
  35. },
  36. // Remove this Todo from *localStorage* and delete its view.
  37. clear: function() {
  38. this.destroy();
  39. this.view.remove();
  40. },
  41. // Set this Todo's location to be the current one
  42. setCurrentLocation: function() {
  43. // TODO(M3): Implement this
  44. var todo = this;
  45. // Check that we're using a supported API
  46. if (Modernizr.geolocation) {
  47. navigator.geolocation.getCurrentPosition(function(position) {
  48. todo.set({'lat': position.coords.latitude,
  49. 'lon': position.coords.longitude});
  50. });
  51. }
  52. }
  53. });
  54. // Todo Collection
  55. // ---------------
  56. // The collection of todos is backed by *localStorage* instead of a remote
  57. // server.
  58. window.TodoList = Backbone.Collection.extend({
  59. // Reference to this collection's model.
  60. model: Todo,
  61. // Save all of the todo items under the `"todos"` namespace.
  62. localStorage: new Store("todos"),
  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. var el = $(this.el);
  110. var model = this.model;
  111. el.html(this.template(this.model.toJSON()));
  112. this.setContent();
  113. return this;
  114. },
  115. // To avoid XSS (not that it would be harmful in this particular app),
  116. // we use `jQuery.text` to set the contents of the todo item.
  117. setContent: function() {
  118. var content = this.model.get('content');
  119. this.$('.todo-content').text(content);
  120. this.input = this.$('.todo-input');
  121. this.input.bind('blur', this.close);
  122. this.input.val(content);
  123. // Render location
  124. if (this.model.get('lat') && this.model.get('lon')) {
  125. this.$('.todo-location').text(
  126. this.model.get('lat') + ',' + this.model.get('lon')
  127. );
  128. }
  129. },
  130. // Toggle the `"done"` state of the model.
  131. toggleDone: function() {
  132. this.model.toggle();
  133. // Since the view will get regenerated every time we change the
  134. // DOM, set a class on the li element
  135. $(this.el).toggleClass('complete', this.model.done);
  136. },
  137. // Switch this view into `"editing"` mode, displaying the input field.
  138. edit: function() {
  139. $(this.el).addClass("editing");
  140. this.input.focus();
  141. },
  142. // Close the `"editing"` mode, saving changes to the todo.
  143. close: function() {
  144. this.model.save({content: this.input.val()});
  145. $(this.el).removeClass("editing");
  146. },
  147. // If you hit `enter`, we're through editing the item.
  148. updateOnEnter: function(e) {
  149. if (e.keyCode == 13) this.close();
  150. },
  151. // Remove this view from the DOM.
  152. remove: function() {
  153. var el = $(this.el);
  154. // Remove the element once the transition is complete
  155. el.bind('webkitTransitionEnd', function() {
  156. el.remove();
  157. });
  158. // Add a "removing" class
  159. el.addClass('removing');
  160. },
  161. // Remove the item, destroy the model.
  162. clear: function() {
  163. this.model.clear();
  164. },
  165. });
  166. // The Application
  167. // ---------------
  168. // Our overall **AppView** is the top-level piece of UI.
  169. window.AppView = Backbone.View.extend({
  170. // Instead of generating a new element, bind to the existing skeleton of
  171. // the App already present in the HTML.
  172. el: $("#todoapp"),
  173. // Our template for the line of statistics at the bottom of the app.
  174. statsTemplate: _.template($('#stats-template').html()),
  175. // Delegated events for creating new items, and clearing completed ones.
  176. events: {
  177. "keypress #new-todo": "createOnEnter",
  178. "keyup #new-todo": "showTooltip",
  179. "click .todo-clear a": "clearCompleted"
  180. },
  181. // At initialization we bind to the relevant events on the `Todos`
  182. // collection, when items are added or changed. Kick things off by
  183. // loading any preexisting todos that might be saved in *localStorage*.
  184. initialize: function() {
  185. _.bindAll(this, 'addOne', 'addAll', 'render');
  186. this.input = this.$("#new-todo");
  187. Todos.bind('add', this.addOne);
  188. Todos.bind('refresh', this.addAll);
  189. Todos.bind('all', this.render);
  190. Todos.fetch();
  191. },
  192. // Re-rendering the App just means refreshing the statistics -- the rest
  193. // of the app doesn't change.
  194. render: function() {
  195. var done = Todos.done().length;
  196. this.$('#todo-stats').html(this.statsTemplate({
  197. total: Todos.length,
  198. done: Todos.done().length,
  199. remaining: Todos.remaining().length
  200. }));
  201. },
  202. // Add a single todo item to the list by creating a view for it, and
  203. // appending its element to the `<ul>`.
  204. addOne: function(todo) {
  205. var view = new TodoView({model: todo});
  206. this.$("#todo-list").append(view.render().el);
  207. },
  208. // Add all items in the **Todos** collection at once.
  209. addAll: function() {
  210. Todos.each(this.addOne);
  211. },
  212. // Generate the attributes for a new Todo item.
  213. newAttributes: function() {
  214. return {
  215. content: this.input.val(),
  216. order: Todos.nextOrder(),
  217. done: false,
  218. old: false
  219. };
  220. },
  221. // If you hit return in the main input field, create new **Todo** model,
  222. // persisting it to *localStorage*.
  223. createOnEnter: function(e) {
  224. if (e.keyCode != 13) return;
  225. var todo = Todos.create(this.newAttributes());
  226. todo.setCurrentLocation();
  227. this.input.val('');
  228. },
  229. // Clear all done todo items, destroying their models.
  230. clearCompleted: function() {
  231. _.each(Todos.done(), function(todo){ todo.clear(); });
  232. return false;
  233. },
  234. // Lazily show the tooltip that tells you to press `enter` to save
  235. // a new todo item, after one second.
  236. showTooltip: function(e) {
  237. var tooltip = this.$(".ui-tooltip-top");
  238. var val = this.input.val();
  239. tooltip.fadeOut();
  240. if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
  241. if (val == '' || val == this.input.attr('placeholder')) return;
  242. var show = function(){ tooltip.show().fadeIn(); };
  243. this.tooltipTimeout = _.delay(show, 1000);
  244. }
  245. });
  246. // Finally, we kick things off by creating the **App**.
  247. window.App = new AppView;
  248. });