Commit 5848399f authored by addyosmani's avatar addyosmani

Updating to rewritten Backbone app.

parents a053160d 1ff6f043
This diff is collapsed.
<!DOCTYPE html> <!doctype html>
<html> <html lang="en">
<head>
<head> <meta charset="utf-8">
<title>Backbone.js</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link href="css/todos.css" media="all" rel="stylesheet" type="text/css"/> <title>Backbone.js</title>
<script src="js/json2.js"></script> <link rel="stylesheet" href="../../assets/base.css"/>
<script src="js/jquery-1.6.4.min.js"></script> </head>
<script src="js/underscore-1.1.6.js"></script> <body>
<script src="js/backbone.js"></script>
<script src="js/backbone-localstorage.js"></script> <section id="todoapp">
<script src="js/todos.js"></script> <header id="header">
</head> <h1>Todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
<body> </header>
<section id="main">
<!-- Todo App Interface --> <input id="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<div id="todoapp"> <ul id="todo-list"></ul>
</section>
<div class="title"> <footer id="footer"></div>
<h1>Todos</h1> </section>
</div> <div id="info">
<p>Double-click to edit a todo</p>
<div class="content"> <p>Created by <a href="http://addyosmani.github.com/todomvc/">Addy Osmani</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
<div id="create-todo"> </footer>
<input id="new-todo" placeholder="What needs to be done?" type="text" />
<span class="ui-tooltip-top" style="display:none;">Press Enter to save this task</span>
</div>
<div id="todos">
<input class="check mark-all-done" type="checkbox"/>
<label for="check-all">Mark all as complete</label>
<ul id="todo-list"></ul>
</div>
<div id="todo-stats"></div>
</div>
</div>
<div id="credits">
Created by
<br />
<a href="http://jgn.me/">J&eacute;r&ocirc;me Gravel-Niquet</a>. <br />Cleanup, edits: <a href="http://addyosmani.com">Addy Osmani</a>.
</div>
<!-- Templates -->
<script type="text/template" id="item-template">
<div class="todo <%= done ? 'done' : '' %>">
<div class="display">
<input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
<label class="todo-content"><%= content %></label>
<span class="todo-destroy"></span>
</div>
<div class="edit">
<input class="todo-input" type="text" value="<%= content %>" />
</div>
</div>
</script>
<script type="text/template" id="stats-template">
<% if (total) { %>
<span class="todo-count">
<span class="number"><%= remaining %></span>
<span class="word"><%= remaining == 1 ? 'item' : 'items' %></span> left.
</span>
<% } %>
<% if (done) { %>
<span class="todo-clear">
<a href="#">
Clear <span class="number-done"><%= done %></span>
completed <span class="word-done"><%= done == 1 ? 'item' : 'items' %></span>
</a>
</span>
<% } %>
</script>
</body>
</html> <script type="text/template" id="item-template">
<div class="view">
<input class="toggle" type="checkbox" <%= completed ? 'checked="checked"' : '' %> />
<label><%= title %></label>
<button class="destroy"></button>
</div>
<input class="edit" type="text" value="<%= title %>" />
</script>
<script type="text/template" id="stats-template">
<span id="todo-count"><strong><%= remaining %></strong> <%= remaining == 1 ? 'item' : 'items' %> left</span>
<ul id="filters">
<li>
<a class="selected" href="#/">All</a>
</li>
<li>
<a href="#/active">Active</a>
</li>
<li>
<a href="#/completed">Completed</a>
</li>
</ul>
<% if (completed) { %>
<button id="clear-completed">Clear completed (<%= completed %>)</button>
<% } %>
</script>
<script src="../../assets/jquery.min.js"></script>
<script src="js/lib/underscore-min.js"></script>
<script src="js/lib/backbone-min.js"></script>
<script src="js/lib/backbone-localstorage.js"></script>
<script src="js/init.js"></script>
<script src="js/models/todo.js"></script>
<script src="js/collections/todos.js"></script>
<script src="js/views/todoView.js"></script>
<script src="js/views/appView.js"></script>
<script src="js/routers/router.js"></script>
<script src="js/app.js"></script>
</body>
</html>
\ No newline at end of file
$(function(){
// Kick things off by creating the **App**.
var App = new window.app.AppView;
});
\ No newline at end of file
This diff is collapsed.
(function() {
'use strict';
// Todo Collection
// ---------------
// The collection of todos is backed by *localStorage* instead of a remote
// server.
var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: window.app.Todo,
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos-backbone"),
// Filter down the list of all todo items that are finished.
completed: function() {
return this.filter(function(todo){ return todo.get('completed'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.completed());
},
// 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.
nextOrder: function() {
if ( !this.length ){
return 1;
}
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: function(todo) {
return todo.get('order');
}
});
// Create our global collection of **Todos**.
window.app.Todos = new TodoList;
})();
// Constants
var ENTER_KEY = 13;
// Setup namespace for the app
window.app = window.app || {};
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
(function() {
'use strict';
// Todo Model
// ----------
// Our basic **Todo** model has `title`, `order`, and `completed` attributes.
window.app.Todo = Backbone.Model.extend({
// Default attributes for the todo.
defaults: {
title: "empty todo...",
completed: false
},
// Ensure that each todo created has `title`.
initialize: function() {
if (!this.get("title")) {
this.set({"title": this.defaults.title});
}
},
// Toggle the `completed` state of this todo item.
toggle: function() {
this.save({completed: !this.get("completed")});
window.app.Todos.trigger('reset');
},
// Remove this Todo from *localStorage* and delete its view.
clear: function() {
this.destroy();
}
});
})();
\ No newline at end of file
(function() {
'use strict';
// Todo Router
// ----------
var Workspace = Backbone.Router.extend({
routes:{
"*filter": "setFilter"
},
setFilter: function(param){
// Set the current filter to be used
window.app.TodoFilter = param.trim() || "";
// Trigger a collection reset/addAll
window.app.Todos.trigger('reset');
}
});
window.app.TodoRouter = new Workspace;
Backbone.history.start();
})();
\ No newline at end of file
// An example Backbone application contributed by
// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple
// [LocalStorage adapter](backbone-localstorage.js)
// to persist Backbone models within your browser.
// Load the application once the DOM is ready, using `jQuery.ready`:
$(function(){
// Todo Model
// ----------
// Our basic **Todo** model has `content`, `order`, and `done` attributes.
var Todo = Backbone.Model.extend({
// Default attributes for the todo.
defaults: {
content: "empty todo...",
done: false
},
// Ensure that each todo created has `content`.
initialize: function() {
if (!this.get("content")) {
this.set({"content": this.defaults.content});
}
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
},
// Remove this Todo from *localStorage* and delete its view.
clear: function() {
this.destroy();
}
});
// Todo Collection
// ---------------
// The collection of todos is backed by *localStorage* instead of a remote
// server.
var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos-backbone"),
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){ return todo.get('done'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.done());
},
// 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.
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: function(todo) {
return todo.get('order');
}
});
// Create our global collection of **Todos**.
var Todos = new TodoList;
// Todo Item View
// --------------
// The DOM element for a todo item...
var TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template($('#item-template').html()),
// The DOM events specific to an item.
events: {
"click .check" : "toggleDone",
"dblclick label.todo-content" : "edit",
"click span.todo-destroy" : "clear",
"keypress .todo-input" : "updateOnEnter",
"blur .todo-input" : "close"
},
// 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
// app, we set a direct reference on the model for convenience.
initialize: function() {
_.bindAll(this, 'render', 'close', 'remove');
this.model.bind('change', this.render);
this.model.bind('destroy', this.remove);
},
// Re-render the contents of the todo item.
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.input = this.$('.todo-input');
return this;
},
// Toggle the `"done"` state of the model.
toggleDone: function() {
this.model.toggle();
},
// Switch this view into `"editing"` mode, displaying the input field.
edit: function() {
$(this.el).addClass("editing");
this.input.focus();
},
// Close the `"editing"` mode, saving changes to the todo.
close: function() {
this.model.save({content: this.input.val()});
$(this.el).removeClass("editing");
},
// If you hit `enter`, we're through editing the item.
updateOnEnter: function(e) {
if (e.keyCode == 13) this.close();
},
// Remove the item, destroy the model.
clear: function() {
this.model.clear();
}
});
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"keyup #new-todo": "showTooltip",
"click .todo-clear a": "clearCompleted",
"click .mark-all-done": "toggleAllComplete"
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function() {
_.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete');
this.input = this.$("#new-todo");
this.allCheckbox = this.$(".mark-all-done")[0];
Todos.bind('add', this.addOne);
Todos.bind('reset', this.addAll);
Todos.bind('all', this.render);
Todos.fetch();
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
var done = Todos.done().length;
var remaining = Todos.remaining().length;
this.$('#todo-stats').html(this.statsTemplate({
total: Todos.length,
done: done,
remaining: remaining
}));
this.allCheckbox.checked = !remaining;
},
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
},
// Add all items in the **Todos** collection at once.
addAll: function() {
Todos.each(this.addOne);
},
// Generate the attributes for a new Todo item.
newAttributes: function() {
return {
content: this.input.val(),
order: Todos.nextOrder(),
done: false
};
},
// If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*.
createOnEnter: function(e) {
if (e.keyCode != 13) return;
Todos.create(this.newAttributes());
this.input.val('');
},
// Clear all done todo items, destroying their models.
clearCompleted: function() {
_.each(Todos.done(), function(todo){ todo.clear(); });
return false;
},
// Lazily show the tooltip that tells you to press `enter` to save
// a new todo item, after one second.
showTooltip: function(e) {
var tooltip = this.$(".ui-tooltip-top");
var val = this.input.val();
tooltip.fadeOut();
if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
if (val == '' || val == this.input.attr('placeholder')) return;
var show = function(){ tooltip.show().fadeIn(); };
this.tooltipTimeout = _.delay(show, 1000);
},
toggleAllComplete: function () {
var done = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'done': done}); });
}
});
// Finally, we kick things off by creating the **App**.
var App = new AppView;
});
This diff is collapsed.
$(function( $ ) {
'use strict';
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
window.app.AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function() {
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
window.app.Todos.on('add', this.addOne, this);
window.app.Todos.on('reset', this.addAll, this);
window.app.Todos.on('all', this.render, this);
this.$footer = $('#footer');
this.$main = $('#main');
window.app.Todos.fetch();
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
var completed = window.app.Todos.completed().length;
var remaining = window.app.Todos.remaining().length;
if (window.app.Todos.length) {
this.$main.show();
this.$footer.show();
this.$footer.html(this.statsTemplate({
completed: completed,
remaining: remaining
}));
this.$('#filters li a')
.removeClass('selected')
.filter("[href='#/" + (window.app.TodoFilter || "") + "']")
.addClass('selected');
} else {
this.$main.hide();
this.$footer.hide();
}
this.allCheckbox.checked = !remaining;
},
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function(todo) {
var view = new window.app.TodoView({model: todo});
$("#todo-list").append(view.render().el);
},
// Add all items in the **Todos** collection at once.
addAll: function() {
this.$("#todo-list").html('');
switch(window.app.TodoFilter){
case "active":
_.each(window.app.Todos.remaining(), this.addOne);
break;
case "completed":
_.each(window.app.Todos.completed(), this.addOne);
break;
default:
window.app.Todos.each(this.addOne, this);
break;
}
},
// Generate the attributes for a new Todo item.
newAttributes: function() {
return {
title: this.input.val().trim(),
order: window.app.Todos.nextOrder(),
completed: false
};
},
// If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*.
createOnEnter: function(e) {
if ( e.keyCode !== ENTER_KEY ){
return;
}
if ( !this.input.val().trim() ){
return;
}
window.app.Todos.create(this.newAttributes());
this.input.val('');
},
// Clear all completed todo items, destroying their models.
clearCompleted: function() {
_.each(window.app.Todos.completed(), function(todo){ todo.clear(); });
return false;
},
toggleAllComplete: function () {
var completed = this.allCheckbox.checked;
window.app.Todos.each(function (todo) { todo.save({'completed': completed}); });
}
});
});
\ No newline at end of file
$(function() {
'use strict';
// Todo Item View
// --------------
// The DOM element for a todo item...
window.app.TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template($('#item-template').html()),
// The DOM events specific to an item.
events: {
"click .toggle" : "togglecompleted",
"dblclick .view" : "edit",
"click .destroy" : "clear",
"keypress .edit" : "updateOnEnter",
"blur .edit" : "close"
},
// 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
// app, we set a direct reference on the model for convenience.
initialize: function() {
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
// Re-render the titles of the todo item.
render: function() {
var $el = $(this.el);
$el.html(this.template(this.model.toJSON()));
$el.toggleClass('completed', this.model.get('completed'));
this.input = this.$('.edit');
return this;
},
// Toggle the `"completed"` state of the model.
togglecompleted: function() {
this.model.toggle();
},
// Switch this view into `"editing"` mode, displaying the input field.
edit: function() {
$(this.el).addClass("editing");
this.input.focus();
},
// Close the `"editing"` mode, saving changes to the todo.
close: function() {
var value = this.input.val().trim();
if ( !value ){
this.clear();
}
this.model.save({title: value});
$(this.el).removeClass("editing");
},
// If you hit `enter`, we're through editing the item.
updateOnEnter: function(e) {
if ( e.keyCode === ENTER_KEY ){
this.close();
}
},
// Remove the item, destroy the model.
clear: function() {
this.model.clear();
}
});
});
\ No newline at end of file
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