PageRenderTime 61ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/backbone-redis/examples/todos/todos.js

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