Commit 5995093b authored by Sindre Sorhus's avatar Sindre Sorhus

Backbone+require app: Convert to tabs

parent ecbd9576
define([ define([
'underscore', 'underscore',
'backbone', 'backbone',
'libs/backbone/localstorage', 'lib/backbone/localstorage',
'models/todo' 'models/todo'
], function(_, Backbone, Store, Todo){ ], function(_, Backbone, Store, Todo){
var TodosCollection = Backbone.Collection.extend({ var TodosCollection = Backbone.Collection.extend({
// Reference to this collection's model. // Reference to this collection's model.
model: Todo, model: Todo,
// Save all of the todo items under the `"todos"` namespace. // Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos-backbone"), localStorage: new Store("todos-backbone"),
// Filter down the list of all todo items that are finished. // Filter down the list of all todo items that are finished.
completed: function() { completed: function() {
return this.filter(function(todo){ return todo.get('completed'); }); return this.filter(function(todo){ return todo.get('completed'); });
}, },
// Filter down the list to only todo items that are still not finished. // Filter down the list to only todo items that are still not finished.
remaining: function() { remaining: function() {
return this.without.apply(this, this.completed()); return this.without.apply(this, this.completed());
}, },
// We keep the Todos in sequential order, despite being saved by unordered // We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items. // GUID in the database. This generates the next order number for new items.
nextOrder: function() { nextOrder: function() {
if ( !this.length ){ if ( !this.length ){
return 1; return 1;
} }
return this.last().get('order') + 1; return this.last().get('order') + 1;
}, },
// Todos are sorted by their original insertion order. // Todos are sorted by their original insertion order.
comparator: function(todo) { comparator: function(todo) {
return todo.get('order'); return todo.get('order');
} }
}); });
return new TodosCollection; return new TodosCollection;
}); });
define(['underscore', 'backbone'], function(_, Backbone) { define(['underscore', 'backbone'], function(_, Backbone) {
var TodoModel = Backbone.Model.extend({ var TodoModel = Backbone.Model.extend({
// Default attributes for the todo. // Default attributes for the todo.
defaults: { defaults: {
title: "empty todo...", title: "empty todo...",
completed: false completed: false
}, },
// Ensure that each todo created has `title`. // Ensure that each todo created has `title`.
initialize: function() { initialize: function() {
if (!this.get("title")) { if (!this.get("title")) {
this.set({"title": this.defaults.title}); this.set({"title": this.defaults.title});
} }
}, },
// Toggle the `completed` state of this todo item. // Toggle the `completed` state of this todo item.
toggle: function() { toggle: function() {
this.save({completed: !this.get("completed")}); this.save({completed: !this.get("completed")});
}, },
// Remove this Todo from *localStorage* and delete its view. // Remove this Todo from *localStorage* and delete its view.
clear: function() { clear: function() {
this.destroy(); this.destroy();
} }
}); });
return TodoModel; return TodoModel;
}); });
......
<span id="todo-count"><strong><%= remaining %></strong> <%= remaining == 1 ? 'item' : 'items' %> left</span> <span id="todo-count"><strong><%= remaining %></strong> <%= remaining == 1 ? 'item' : 'items' %> left</span>
<ul id="filters"> <ul id="filters">
<li> <li>
<a class="selected" href="#/">All</a> <a class="selected" href="#/">All</a>
</li> </li>
<li> <li>
<a href="#/active">Active</a> <a href="#/active">Active</a>
</li> </li>
<li> <li>
<a href="#/completed">Completed</a> <a href="#/completed">Completed</a>
</li> </li>
</ul> </ul>
<% if (completed) { %> <% if (completed) { %>
<button id="clear-completed">Clear completed (<%= completed %>)</button> <button id="clear-completed">Clear completed (<%= completed %>)</button>
<% } %> <% } %>
\ No newline at end of file
<div class="view"> <div class="view">
<input class="toggle" type="checkbox" <%= completed ? 'checked="checked"' : '' %> /> <input class="toggle" type="checkbox" <%= completed ? 'checked="checked"' : '' %> />
<label><%- title %></label> <label><%- title %></label>
<button class="destroy"></button> <button class="destroy"></button>
</div> </div>
<input class="edit" type="text" value="<%- title %>" /> <input class="edit" type="text" value="<%- title %>" />
define([ define([
'jquery', 'jquery',
'underscore', 'underscore',
'backbone', 'backbone',
'collections/todos', 'collections/todos',
'views/todos', 'views/todos',
'text!templates/stats.html', 'text!templates/stats.html',
'common' 'common'
], function($, _, Backbone, Todos, TodoView, statsTemplate, Common){ ], function($, _, Backbone, Todos, TodoView, statsTemplate, Common){
var AppView = Backbone.View.extend({ var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of // Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML. // the App already present in the HTML.
el: $("#todoapp"), el: $("#todoapp"),
// Compile our stats template // Compile our stats template
template: _.template(statsTemplate), template: _.template(statsTemplate),
// Delegated events for creating new items, and clearing completed ones. // Delegated events for creating new items, and clearing completed ones.
events: { events: {
"keypress #new-todo": "createOnEnter", "keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted", "click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete" "click #toggle-all": "toggleAllComplete"
}, },
// At initialization we bind to the relevant events on the `Todos` // At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by // collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*. // loading any preexisting todos that might be saved in *localStorage*.
initialize: function() { initialize: function() {
this.input = this.$("#new-todo"); this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0]; this.allCheckbox = this.$("#toggle-all")[0];
Todos.on('add', this.addOne, this); Todos.on('add', this.addOne, this);
Todos.on('reset', this.addAll, this); Todos.on('reset', this.addAll, this);
Todos.on('all', this.render, this); Todos.on('all', this.render, this);
this.$footer = $('#footer'); this.$footer = $('#footer');
this.$main = $('#main'); this.$main = $('#main');
Todos.fetch(); Todos.fetch();
}, },
// Re-rendering the App just means refreshing the statistics -- the rest // Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change. // of the app doesn't change.
render: function() { render: function() {
var completed = Todos.completed().length; var completed = Todos.completed().length;
var remaining = Todos.remaining().length; var remaining = Todos.remaining().length;
if (Todos.length) { if (Todos.length) {
this.$main.show(); this.$main.show();
this.$footer.show(); this.$footer.show();
this.$footer.html(this.template({ this.$footer.html(this.template({
completed: completed, completed: completed,
remaining: remaining remaining: remaining
})); }));
this.$('#filters li a') this.$('#filters li a')
.removeClass('selected') .removeClass('selected')
.filter("[href='#/" + (Common.TodoFilter || "") + "']") .filter("[href='#/" + (Common.TodoFilter || "") + "']")
.addClass('selected'); .addClass('selected');
} else { } else {
this.$main.hide(); this.$main.hide();
this.$footer.hide(); this.$footer.hide();
} }
this.allCheckbox.checked = !remaining; this.allCheckbox.checked = !remaining;
}, },
// Add a single todo item to the list by creating a view for it, and // Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`. // appending its element to the `<ul>`.
addOne: function(todo) { addOne: function(todo) {
var view = new TodoView({model: todo}); var view = new TodoView({model: todo});
$("#todo-list").append(view.render().el); $("#todo-list").append(view.render().el);
}, },
// Add all items in the **Todos** collection at once. // Add all items in the **Todos** collection at once.
addAll: function() { addAll: function() {
this.$("#todo-list").html(''); this.$("#todo-list").html('');
switch(Common.TodoFilter){ switch(Common.TodoFilter){
case "active": case "active":
_.each(Todos.remaining(), this.addOne); _.each(Todos.remaining(), this.addOne);
break; break;
case "completed": case "completed":
_.each(Todos.completed(), this.addOne); _.each(Todos.completed(), this.addOne);
break; break;
default: default:
Todos.each(this.addOne, this); Todos.each(this.addOne, this);
break; break;
} }
}, },
// Generate the attributes for a new Todo item. // Generate the attributes for a new Todo item.
newAttributes: function() { newAttributes: function() {
return { return {
title: this.input.val().trim(), title: this.input.val().trim(),
order: Todos.nextOrder(), order: Todos.nextOrder(),
completed: false completed: false
}; };
}, },
// If you hit return in the main input field, create new **Todo** model, // If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*. // persisting it to *localStorage*.
createOnEnter: function(e) { createOnEnter: function(e) {
if ( e.keyCode !== Common.ENTER_KEY ){ if ( e.keyCode !== Common.ENTER_KEY ){
return; return;
} }
if ( !this.input.val().trim() ){ if ( !this.input.val().trim() ){
return; return;
} }
Todos.create(this.newAttributes()); Todos.create(this.newAttributes());
this.input.val(''); this.input.val('');
}, },
// Clear all completed todo items, destroying their models. // Clear all completed todo items, destroying their models.
clearCompleted: function() { clearCompleted: function() {
_.each(Todos.completed(), function(todo){ todo.clear(); }); _.each(Todos.completed(), function(todo){ todo.clear(); });
return false; return false;
}, },
toggleAllComplete: function () { toggleAllComplete: function () {
var completed = this.allCheckbox.checked; var completed = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'completed': completed}); }); Todos.each(function (todo) { todo.save({'completed': completed}); });
} }
}); });
return AppView; return AppView;
}); });
define([ define([
'jquery', 'jquery',
'underscore', 'underscore',
'backbone', 'backbone',
'text!templates/todos.html', 'text!templates/todos.html',
'common' 'common'
], function($, _, Backbone, todosTemplate, Common){ ], function($, _, Backbone, todosTemplate, Common){
var TodoView = Backbone.View.extend({ var TodoView = Backbone.View.extend({
//... is a list tag. //... is a list tag.
tagName: "li", tagName: "li",
template: _.template(todosTemplate), template: _.template(todosTemplate),
// The DOM events specific to an item. // The DOM events specific to an item.
events: { events: {
"click .toggle" : "togglecompleted", "click .toggle" : "togglecompleted",
"dblclick .view" : "edit", "dblclick .view" : "edit",
"click .destroy" : "clear", "click .destroy" : "clear",
"keypress .edit" : "updateOnEnter", "keypress .edit" : "updateOnEnter",
"blur .edit" : "close" "blur .edit" : "close"
}, },
// The TodoView listens for changes to its model, re-rendering. Since there's // The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this // a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience. // app, we set a direct reference on the model for convenience.
initialize: function() { initialize: function() {
this.model.on('change', this.render, this); this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this); this.model.on('destroy', this.remove, this);
}, },
// Re-render the titles of the todo item. // Re-render the titles of the todo item.
render: function() { render: function() {
var $el = $(this.el); var $el = $(this.el);
$el.html(this.template(this.model.toJSON())); $el.html(this.template(this.model.toJSON()));
$el.toggleClass('completed', this.model.get('completed')); $el.toggleClass('completed', this.model.get('completed'));
this.input = this.$('.edit'); this.input = this.$('.edit');
return this; return this;
}, },
// Toggle the `"completed"` state of the model. // Toggle the `"completed"` state of the model.
togglecompleted: function() { togglecompleted: function() {
this.model.toggle(); this.model.toggle();
}, },
// Switch this view into `"editing"` mode, displaying the input field. // Switch this view into `"editing"` mode, displaying the input field.
edit: function() { edit: function() {
$(this.el).addClass("editing"); $(this.el).addClass("editing");
this.input.focus(); this.input.focus();
}, },
// Close the `"editing"` mode, saving changes to the todo. // Close the `"editing"` mode, saving changes to the todo.
close: function() { close: function() {
var value = this.input.val().trim(); var value = this.input.val().trim();
if ( !value ){ if ( !value ){
this.clear(); this.clear();
} }
this.model.save({title: value}); this.model.save({title: value});
$(this.el).removeClass("editing"); $(this.el).removeClass("editing");
}, },
// If you hit `enter`, we're through editing the item. // If you hit `enter`, we're through editing the item.
updateOnEnter: function(e) { updateOnEnter: function(e) {
if ( e.keyCode === Common.ENTER_KEY ){ if ( e.keyCode === Common.ENTER_KEY ){
this.close(); this.close();
} }
}, },
// Remove the item, destroy the model. // Remove the item, destroy the model.
clear: function() { clear: function() {
this.model.clear(); this.model.clear();
} }
}); });
return TodoView; return TodoView;
}); });
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment