Commit a5c3fbe9 authored by addyosmani's avatar addyosmani

Fixes #73 - updating Backbone + RequireJS app incl. update to RJS 2.0. Adding...

Fixes #73 - updating Backbone + RequireJS app incl. update to RJS 2.0. Adding tweaks to existing BB app.
parent c226bcd5
......@@ -22,7 +22,7 @@
</section>
<div id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://addyosmani.github.com/todomvc/">Addy Osmani</a></p>
<p>Written by <a href="http://addyosmani.github.com/todomvc/">Addy Osmani</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
......@@ -62,8 +62,8 @@
<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/views/todos.js"></script>
<script src="js/views/app.js"></script>
<script src="js/routers/router.js"></script>
<script src="js/app.js"></script>
......
......@@ -23,7 +23,6 @@
// 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.
......
This diff is collapsed.
<!doctype html>
<html lang="en">
<head>
<title>Todo App - Backbone - RequireJs - Thomas Davis</title>
<link rel="stylesheet" href="css/todos.css">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Backbone.js</title>
<link rel="stylesheet" href="../../assets/base.css"/>
<script data-main="js/main" src="js/libs/require/require.js"></script>
</head>
<body>
<div id="todoapp">
<div class="title">
<h1>Todos</h1>
</div>
<div class="content">
<div id="create-todo">
<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>
<section id="todoapp">
<header id="header">
<h1>Todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
</header>
<section id="main">
<input id="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list"></ul>
</section>
<footer id="footer"></div>
</section>
<div id="info">
<p>Double-click to edit a todo</p>
<p>Written by <a href="http://addyosmani.github.com/todomvc/">Addy Osmani</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
<div id="todo-stats"></div>
</body>
</html>
</div>
</div>
<div id="credits">
<p>Modularized by
<a href="http://backbonetutorials.com">Thomas Davis</a>.
Originally by
<a href="http://jgn.me/">J&eacute;r&ocirc;me Gravel-Niquet</a>.
</p>
</div>
</body>
</html>
\ No newline at end of file
......@@ -11,22 +11,24 @@ define([
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos-backbone-require"),
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'); });
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.done());
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;
if ( !this.length ){
return 1;
}
return this.last().get('order') + 1;
},
......
define([], function(){
return {
// Which filter are we using?
TodoFilter: "", // empty, active, completed
// What is the enter key constant?
ENTER_KEY: 13
};
});
// Author: Thomas Davis <thomasalwyndavis@gmail.com>
// Filename: main.js
// Require.js allows us to configure shortcut alias
require.config({
paths: {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone',
text: 'libs/require/text'
}
// The shim config allows us to configure dependencies for
// scripts that do not call define() to register a module
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
},
paths: {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone',
text: 'libs/require/text'
}
});
require(['views/app'], function(AppView){
require(['views/app', 'routers/router'], function( AppView, Workspace ){
// Initialize routing and start Backbone.history()
var TodoRouter = new Workspace;
Backbone.history.start();
// Initialize the application view
var app_view = new AppView;
});
......@@ -3,27 +3,37 @@ define(['underscore', 'backbone'], function(_, Backbone) {
// Default attributes for the todo.
defaults: {
content: "empty todo...",
done: false
title: "empty todo...",
completed: false
},
// Ensure that each todo created has `content`.
// Ensure that each todo created has `title`.
initialize: function() {
if (!this.get("content")) {
this.set({"content": this.defaults.content});
if (!this.get("title")) {
this.set({"title": this.defaults.title});
}
},
// Toggle the `done` state of this todo item.
// Toggle the `completed` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
this.save({completed: !this.get("completed")});
},
// Remove this Todo from *localStorage*.
// Remove this Todo from *localStorage* and delete its view.
clear: function() {
this.destroy();
}
});
return TodoModel;
});
define(['jquery','backbone', 'collections/todos', 'common'], function($, Backbone, Todos, Common){
var Workspace = Backbone.Router.extend({
routes:{
"*filter": "setFilter"
},
setFilter: function(param){
// Set the current filter to be used
Common.TodoFilter = param.trim() || "";
// Trigger a collection reset/addAll
Todos.trigger('reset');
}
});
return Workspace;
});
\ No newline at end of file
<% 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>
<% } %>
<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>
<% } %>
\ No newline at end of file
<div class="todo <%= done ? 'done' : '' %>">
<div class="display">
<input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
<div class="todo-content"><%= content %></div>
<span class="todo-destroy"></span>
</div>
<div class="edit">
<input class="todo-input" type="text" value="<%= content %>" />
</div>
</div>
<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 %>" />
\ No newline at end of file
......@@ -4,37 +4,41 @@ define([
'backbone',
'collections/todos',
'views/todos',
'text!templates/stats.html'
], function($, _, Backbone, Todos, TodoView, statsTemplate){
'text!templates/stats.html',
'common'
], function($, _, Backbone, Todos, TodoView, statsTemplate, Common){
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(statsTemplate),
// Compile our stats template
template: _.template(statsTemplate),
// 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"
"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() {
_.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete');
this.input = this.$("#new-todo");
this.allCheckbox = this.$(".mark-all-done")[0];
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
Todos.on('add', this.addOne, this);
Todos.on('reset', this.addAll, this);
Todos.on('all', this.render, this);
Todos.bind('add', this.addOne);
Todos.bind('reset', this.addAll);
Todos.bind('all', this.render);
this.$footer = $('#footer');
this.$main = $('#main');
Todos.fetch();
},
......@@ -42,14 +46,29 @@ define([
// 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 completed = Todos.completed().length;
var remaining = Todos.remaining().length;
this.$('#todo-stats').html(this.statsTemplate({
total: Todos.length,
done: done,
remaining: remaining
}));
if (Todos.length) {
this.$main.show();
this.$footer.show();
this.$footer.html(this.template({
completed: completed,
remaining: remaining
}));
this.$('#filters li a')
.removeClass('selected')
.filter("[href='#/" + (Common.TodoFilter || "") + "']")
.addClass('selected');
} else {
this.$main.hide();
this.$footer.hide();
}
this.allCheckbox.checked = !remaining;
},
......@@ -58,55 +77,66 @@ define([
// appending its element to the `<ul>`.
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
$("#todo-list").append(view.render().el);
},
// Add all items in the **Todos** collection at once.
addAll: function() {
Todos.each(this.addOne);
this.$("#todo-list").html('');
switch(Common.TodoFilter){
case "active":
_.each(Todos.remaining(), this.addOne);
break;
case "completed":
_.each(Todos.completed(), this.addOne);
break;
default:
Todos.each(this.addOne, this);
break;
}
},
// Generate the attributes for a new Todo item.
newAttributes: function() {
return {
content: this.input.val(),
order: Todos.nextOrder(),
done: false
title: this.input.val().trim(),
order: 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 != 13) return;
if ( e.keyCode !== Common.ENTER_KEY ){
return;
}
if ( !this.input.val().trim() ){
return;
}
Todos.create(this.newAttributes());
this.input.val('');
},
// Clear all done todo items, destroying their models.
// Clear all completed todo items, destroying their models.
clearCompleted: function() {
_.each(Todos.done(), function(todo){ todo.clear(); });
_.each(Todos.completed(), 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);
},
// Change each todo so that it's `done` state matches the check all
toggleAllComplete: function () {
var done = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'done': done}); });
var completed = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'completed': completed}); });
}
});
return AppView;
});
......@@ -2,43 +2,45 @@ define([
'jquery',
'underscore',
'backbone',
'text!templates/todos.html'
], function($, _, Backbone, todosTemplate){
'text!templates/todos.html',
'common'
], function($, _, Backbone, todosTemplate, Common){
var TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template(todosTemplate),
// The DOM events specific to an item.
events: {
"click .check" : "toggleDone",
"dblclick div.todo-content" : "edit",
"click span.todo-destroy" : "clear",
"keypress .todo-input" : "updateOnEnter",
"blur .todo-input" : "close"
"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() {
_.bindAll(this, 'render', 'close', 'remove');
this.model.bind('change', this.render);
this.model.bind('destroy', this.remove);
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
// Re-render the contents of the todo item.
// Re-render the titles of the todo item.
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.input = this.$('.todo-input');
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 `"done"` state of the model.
toggleDone: function() {
// Toggle the `"completed"` state of the model.
togglecompleted: function() {
this.model.toggle();
},
......@@ -50,20 +52,29 @@ define([
// Close the `"editing"` mode, saving changes to the todo.
close: function() {
this.model.save({content: this.input.val()});
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 == 13) this.close();
if ( e.keyCode === Common.ENTER_KEY ){
this.close();
}
},
// Remove the item, destroy the model.
clear: function() {
this.model.clear();
}
});
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