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 @@ ...@@ -22,7 +22,7 @@
</section> </section>
<div id="info"> <div id="info">
<p>Double-click to edit a todo</p> <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> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer> </footer>
...@@ -62,8 +62,8 @@ ...@@ -62,8 +62,8 @@
<script src="js/init.js"></script> <script src="js/init.js"></script>
<script src="js/models/todo.js"></script> <script src="js/models/todo.js"></script>
<script src="js/collections/todos.js"></script> <script src="js/collections/todos.js"></script>
<script src="js/views/todoView.js"></script> <script src="js/views/todos.js"></script>
<script src="js/views/appView.js"></script> <script src="js/views/app.js"></script>
<script src="js/routers/router.js"></script> <script src="js/routers/router.js"></script>
<script src="js/app.js"></script> <script src="js/app.js"></script>
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
// 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")});
window.app.Todos.trigger('reset');
}, },
// Remove this Todo from *localStorage* and delete its view. // Remove this Todo from *localStorage* and delete its view.
......
This diff is collapsed.
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<title>Todo App - Backbone - RequireJs - Thomas Davis</title> <meta charset="utf-8">
<link rel="stylesheet" href="css/todos.css"> <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> <script data-main="js/main" src="js/libs/require/require.js"></script>
</head> </head>
<body> <body>
<div id="todoapp"> <section id="todoapp">
<header id="header">
<div class="title"> <h1>Todos</h1>
<h1>Todos</h1> <input id="new-todo" placeholder="What needs to be done?" autofocus>
</div> </header>
<section id="main">
<div class="content"> <input id="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<div id="create-todo"> <ul id="todo-list"></ul>
<input id="new-todo" placeholder="What needs to be done?" type="text" /> </section>
<span class="ui-tooltip-top" style="display:none;">Press Enter to save this task</span> <footer id="footer"></div>
</div> </section>
<div id="info">
<div id="todos"> <p>Double-click to edit a todo</p>
<input class="check mark-all-done" type="checkbox"/> <p>Written by <a href="http://addyosmani.github.com/todomvc/">Addy Osmani</a></p>
<label for="check-all">Mark all as complete</label> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
<ul id="todo-list"></ul> </footer>
</div>
<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([ ...@@ -11,22 +11,24 @@ define([
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-require"), 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.
done: function() { completed: function() {
return this.filter(function(todo){ return todo.get('done'); }); 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.done()); 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) return 1; if ( !this.length ){
return 1;
}
return this.last().get('order') + 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.js allows us to configure shortcut alias
require.config({ require.config({
paths: {
jquery: 'libs/jquery/jquery-min', // The shim config allows us to configure dependencies for
underscore: 'libs/underscore/underscore', // scripts that do not call define() to register a module
backbone: 'libs/backbone/backbone', shim: {
text: 'libs/require/text' '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; var app_view = new AppView;
}); });
...@@ -3,27 +3,37 @@ define(['underscore', 'backbone'], function(_, Backbone) { ...@@ -3,27 +3,37 @@ define(['underscore', 'backbone'], function(_, Backbone) {
// Default attributes for the todo. // Default attributes for the todo.
defaults: { defaults: {
content: "empty todo...", title: "empty todo...",
done: false completed: false
}, },
// Ensure that each todo created has `content`. // Ensure that each todo created has `title`.
initialize: function() { initialize: function() {
if (!this.get("content")) { if (!this.get("title")) {
this.set({"content": this.defaults.content}); this.set({"title": this.defaults.title});
} }
}, },
// Toggle the `done` state of this todo item. // Toggle the `completed` state of this todo item.
toggle: function() { 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() { clear: function() {
this.destroy(); this.destroy();
} }
}); });
return TodoModel; 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 id="todo-count"><strong><%= remaining %></strong> <%= remaining == 1 ? 'item' : 'items' %> left</span>
<span class="todo-count"> <ul id="filters">
<span class="number"><%= remaining %></span> <li>
<span class="word"><%= remaining == 1 ? 'item' : 'items' %></span> left. <a class="selected" href="#/">All</a>
</span> </li>
<% } %> <li>
<% if (done) { %> <a href="#/active">Active</a>
<span class="todo-clear"> </li>
<a href="#"> <li>
Clear <span class="number-done"><%= done %></span> <a href="#/completed">Completed</a>
completed <span class="word-done"><%= done == 1 ? 'item' : 'items' %></span> </li>
</a> </ul>
</span> <% if (completed) { %>
<% } %> <button id="clear-completed">Clear completed (<%= completed %>)</button>
<% } %>
\ No newline at end of file
<div class="todo <%= done ? 'done' : '' %>"> <div class="view">
<div class="display"> <input class="toggle" type="checkbox" <%= completed ? 'checked="checked"' : '' %> />
<input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> /> <label><%= title %></label>
<div class="todo-content"><%= content %></div> <button class="destroy"></button>
<span class="todo-destroy"></span> </div>
</div> <input class="edit" type="text" value="<%= title %>" />
<div class="edit"> \ No newline at end of file
<input class="todo-input" type="text" value="<%= content %>" />
</div>
</div>
...@@ -4,37 +4,41 @@ define([ ...@@ -4,37 +4,41 @@ define([
'backbone', 'backbone',
'collections/todos', 'collections/todos',
'views/todos', 'views/todos',
'text!templates/stats.html' 'text!templates/stats.html',
], 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"),
// Our template for the line of statistics at the bottom of the app. // Compile our stats template
statsTemplate: _.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",
"keyup #new-todo": "showTooltip", "click #clear-completed": "clearCompleted",
"click .todo-clear a": "clearCompleted", "click #toggle-all": "toggleAllComplete"
"click .mark-all-done": "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() {
_.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete');
this.input = this.$("#new-todo"); this.input = this.$("#new-todo");
this.allCheckbox = this.$(".mark-all-done")[0]; 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); this.$footer = $('#footer');
Todos.bind('reset', this.addAll); this.$main = $('#main');
Todos.bind('all', this.render);
Todos.fetch(); Todos.fetch();
}, },
...@@ -42,14 +46,29 @@ define([ ...@@ -42,14 +46,29 @@ define([
// 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 done = Todos.done().length; var completed = Todos.completed().length;
var remaining = Todos.remaining().length; var remaining = Todos.remaining().length;
this.$('#todo-stats').html(this.statsTemplate({ if (Todos.length) {
total: Todos.length, this.$main.show();
done: done, this.$footer.show();
remaining: remaining
})); 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; this.allCheckbox.checked = !remaining;
}, },
...@@ -58,55 +77,66 @@ define([ ...@@ -58,55 +77,66 @@ define([
// 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});
this.$("#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() {
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. // Generate the attributes for a new Todo item.
newAttributes: function() { newAttributes: function() {
return { return {
content: this.input.val(), title: this.input.val().trim(),
order: Todos.nextOrder(), order: Todos.nextOrder(),
done: 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 != 13) return;
if ( e.keyCode !== Common.ENTER_KEY ){
return;
}
if ( !this.input.val().trim() ){
return;
}
Todos.create(this.newAttributes()); Todos.create(this.newAttributes());
this.input.val(''); this.input.val('');
}, },
// Clear all done todo items, destroying their models. // Clear all completed todo items, destroying their models.
clearCompleted: function() { clearCompleted: function() {
_.each(Todos.done(), function(todo){ todo.clear(); }); _.each(Todos.completed(), function(todo){ todo.clear(); });
return false; 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 () { toggleAllComplete: function () {
var done = this.allCheckbox.checked; var completed = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'done': done}); }); Todos.each(function (todo) { todo.save({'completed': completed}); });
} }
}); });
return AppView; return AppView;
}); });
...@@ -2,43 +2,45 @@ define([ ...@@ -2,43 +2,45 @@ define([
'jquery', 'jquery',
'underscore', 'underscore',
'backbone', 'backbone',
'text!templates/todos.html' 'text!templates/todos.html',
], 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",
// Cache the template function for a single item.
template: _.template(todosTemplate), template: _.template(todosTemplate),
// The DOM events specific to an item. // The DOM events specific to an item.
events: { events: {
"click .check" : "toggleDone", "click .toggle" : "togglecompleted",
"dblclick div.todo-content" : "edit", "dblclick .view" : "edit",
"click span.todo-destroy" : "clear", "click .destroy" : "clear",
"keypress .todo-input" : "updateOnEnter", "keypress .edit" : "updateOnEnter",
"blur .todo-input" : "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() {
_.bindAll(this, 'render', 'close', 'remove'); this.model.on('change', this.render, this);
this.model.bind('change', this.render); this.model.on('destroy', this.remove, this);
this.model.bind('destroy', this.remove);
}, },
// Re-render the contents of the todo item. // Re-render the titles of the todo item.
render: function() { render: function() {
$(this.el).html(this.template(this.model.toJSON())); var $el = $(this.el);
this.input = this.$('.todo-input'); $el.html(this.template(this.model.toJSON()));
$el.toggleClass('completed', this.model.get('completed'));
this.input = this.$('.edit');
return this; return this;
}, },
// Toggle the `"done"` state of the model. // Toggle the `"completed"` state of the model.
toggleDone: function() { togglecompleted: function() {
this.model.toggle(); this.model.toggle();
}, },
...@@ -50,20 +52,29 @@ define([ ...@@ -50,20 +52,29 @@ define([
// Close the `"editing"` mode, saving changes to the todo. // Close the `"editing"` mode, saving changes to the todo.
close: function() { 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"); $(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 == 13) this.close(); if ( e.keyCode === Common.ENTER_KEY ){
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