Commit 43cda3d5 authored by Sindre Sorhus's avatar Sindre Sorhus

Backbone app: Cleanup, code style, etc

parent 4edb65d7
...@@ -3,11 +3,13 @@ ...@@ -3,11 +3,13 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Backbone.js</title> <title>Backbone.js • TodoMVC</title>
<link rel="stylesheet" href="../../assets/base.css"/> <link rel="stylesheet" href="../../assets/base.css">
<!--[if IE]>
<script src="../../assets/ie.js"></script>
<![endif]-->
</head> </head>
<body> <body>
<section id="todoapp"> <section id="todoapp">
<header id="header"> <header id="header">
<h1>todos</h1> <h1>todos</h1>
...@@ -22,22 +24,19 @@ ...@@ -22,22 +24,19 @@
</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>Written by <a href="http://addyosmani.github.com/todomvc/">Addy Osmani</a></p> <p>Written by <a href="https://github.com/addyosmani">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>
</div> </div>
<script type="text/template" id="item-template"> <script type="text/template" id="item-template">
<div class="view"> <div class="view">
<input class="toggle" type="checkbox" <%= completed ? 'checked="checked"' : '' %> /> <input class="toggle" type="checkbox" <%= completed ? '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" value="<%= title %>">
</script> </script>
<script type="text/template" id="stats-template"> <script type="text/template" id="stats-template">
<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>
...@@ -53,19 +52,16 @@ ...@@ -53,19 +52,16 @@
<button id="clear-completed">Clear completed (<%= completed %>)</button> <button id="clear-completed">Clear completed (<%= completed %>)</button>
<% } %> <% } %>
</script> </script>
<script src="../../assets/jquery.min.js"></script>
<script src="../../assets/jquery.min.js"></script> <script src="js/lib/underscore-min.js"></script>
<script src="js/lib/underscore-min.js"></script> <script src="js/lib/backbone-min.js"></script>
<script src="js/lib/backbone-min.js"></script> <script src="js/lib/backbone-localstorage.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/init.js"></script> <script src="js/collections/todos.js"></script>
<script src="js/models/todo.js"></script> <script src="js/views/todos.js"></script>
<script src="js/collections/todos.js"></script> <script src="js/views/app.js"></script>
<script src="js/views/todos.js"></script> <script src="js/routers/router.js"></script>
<script src="js/views/app.js"></script> <script src="js/app.js"></script>
<script src="js/routers/router.js"></script>
<script src="js/app.js"></script>
</body> </body>
</html> </html>
\ No newline at end of file
$(function(){ $(function() {
// Kick things off by creating the **App**. // Kick things off by creating the **App**.
var App = new window.app.AppView; var App = new window.app.AppView;
}); });
\ No newline at end of file
...@@ -12,29 +12,31 @@ ...@@ -12,29 +12,31 @@
model: window.app.Todo, model: window.app.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');
} }
}); });
...@@ -42,4 +44,4 @@ ...@@ -42,4 +44,4 @@
// Create our global collection of **Todos**. // Create our global collection of **Todos**.
window.app.Todos = new TodoList; window.app.Todos = new TodoList;
})(); }());
// Constants // Constants
var ENTER_KEY = 13; var ENTER_KEY = 13;
// Setup namespace for the app // Setup namespace for the app
window.app = window.app || {}; window.app = window.app || {};
\ No newline at end of file
...@@ -9,20 +9,24 @@ ...@@ -9,20 +9,24 @@
// Default attributes for the todo. // Default attributes for the todo.
defaults: { defaults: {
title: "empty todo...", title: '',
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.
...@@ -32,5 +36,4 @@ ...@@ -32,5 +36,4 @@
}); });
}());
})();
\ No newline at end of file
...@@ -5,23 +5,20 @@ ...@@ -5,23 +5,20 @@
// ---------- // ----------
var Workspace = Backbone.Router.extend({ var Workspace = Backbone.Router.extend({
routes:{ routes:{
"*filter": "setFilter" '*filter': 'setFilter'
}, },
setFilter: function(param){ setFilter: function( param ) {
// Set the current filter to be used // Set the current filter to be used
window.app.TodoFilter = param.trim() || ""; window.app.TodoFilter = param.trim() || '';
// Trigger a collection reset/addAll // Trigger a collection reset/addAll
window.app.Todos.trigger('reset'); window.app.Todos.trigger('reset');
} }
}); });
window.app.TodoRouter = new Workspace; window.app.TodoRouter = new Workspace();
Backbone.history.start(); Backbone.history.start();
})(); }());
\ No newline at end of file
...@@ -9,29 +9,28 @@ $(function( $ ) { ...@@ -9,29 +9,28 @@ $(function( $ ) {
// 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. // Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()), statsTemplate: _.template( $('#stats-template').html() ),
// 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.allCheckbox = this.$('#toggle-all')[0];
this.input = this.$("#new-todo"); window.app.Todos.on( 'add', this.addOne, this );
this.allCheckbox = this.$("#toggle-all")[0]; window.app.Todos.on( 'reset', this.addAll, this );
window.app.Todos.on( 'all', this.render, this );
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.$footer = $('#footer');
this.$main = $('#main'); this.$main = $('#main');
...@@ -45,22 +44,19 @@ $(function( $ ) { ...@@ -45,22 +44,19 @@ $(function( $ ) {
var completed = window.app.Todos.completed().length; var completed = window.app.Todos.completed().length;
var remaining = window.app.Todos.remaining().length; var remaining = window.app.Todos.remaining().length;
if (window.app.Todos.length) { if ( window.app.Todos.length ) {
this.$main.show(); this.$main.show();
this.$footer.show(); this.$footer.show();
this.$footer.html(this.statsTemplate({ this.$footer.html(this.statsTemplate({
completed: completed, completed: completed,
remaining: remaining remaining: remaining
})); }));
this.$('#filters li a') this.$('#filters li a')
.removeClass('selected') .removeClass('selected')
.filter("[href='#/" + (window.app.TodoFilter || "") + "']") .filter('[href="#/' + ( window.app.TodoFilter || '' ) + '"]')
.addClass('selected'); .addClass('selected');
} else { } else {
this.$main.hide(); this.$main.hide();
this.$footer.hide(); this.$footer.hide();
...@@ -71,28 +67,26 @@ $(function( $ ) { ...@@ -71,28 +67,26 @@ $(function( $ ) {
// 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 window.app.TodoView({model: todo}); var view = new window.app.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( window.app.TodoFilter ) {
case 'active':
switch(window.app.TodoFilter){ _.each( window.app.Todos.remaining(), this.addOne );
case "active":
_.each(window.app.Todos.remaining(), this.addOne);
break; break;
case "completed": case 'completed':
_.each(window.app.Todos.completed(), this.addOne); _.each( window.app.Todos.completed(), this.addOne );
break; break;
default: default:
window.app.Todos.each(this.addOne, this); window.app.Todos.each( this.addOne, this );
break; break;
} }
}, },
// Generate the attributes for a new Todo item. // Generate the attributes for a new Todo item.
...@@ -106,31 +100,32 @@ $(function( $ ) { ...@@ -106,31 +100,32 @@ $(function( $ ) {
// 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.which !== ENTER_KEY || !this.input.val().trim() ) {
if ( e.keyCode !== ENTER_KEY ){
return; return;
} }
if ( !this.input.val().trim() ){ window.app.Todos.create( this.newAttributes() );
return;
}
window.app.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(window.app.Todos.completed(), function(todo){ todo.clear(); }); _.each( window.app.Todos.completed(), function( todo ) {
todo.clear();
});
return false; return false;
}, },
toggleAllComplete: function () { toggleAllComplete: function() {
var completed = this.allCheckbox.checked; var completed = this.allCheckbox.checked;
window.app.Todos.each(function (todo) { todo.save({'completed': completed}); });
window.app.Todos.each(function( todo ) {
todo.save({
'completed': completed
});
});
} }
}); });
});
});
\ No newline at end of file
...@@ -8,33 +8,34 @@ $(function() { ...@@ -8,33 +8,34 @@ $(function() {
window.app.TodoView = Backbone.View.extend({ window.app.TodoView = Backbone.View.extend({
//... is a list tag. //... is a list tag.
tagName: "li", tagName: 'li',
// Cache the template function for a single item. // Cache the template function for a single item.
template: _.template($('#item-template').html()), template: _.template( $('#item-template').html() ),
// 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.toggleClass('completed', this.model.get('completed')); $el.html( this.template( this.model.toJSON() ) );
$el.toggleClass( 'completed', this.model.get('completed') );
this.input = this.$('.edit'); this.input = this.$('.edit');
return this; return this;
...@@ -47,7 +48,7 @@ $(function() { ...@@ -47,7 +48,7 @@ $(function() {
// 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();
}, },
...@@ -55,17 +56,17 @@ $(function() { ...@@ -55,17 +56,17 @@ $(function() {
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 === ENTER_KEY ){ if ( e.which === ENTER_KEY ) {
this.close(); this.close();
} }
}, },
...@@ -75,5 +76,4 @@ $(function() { ...@@ -75,5 +76,4 @@ $(function() {
this.model.clear(); 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