Debian Codegraph @

examples/todos/todos.js

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