Skip to content

Commit

Permalink
TodoMVC Backbone w/ RequireJS example
Browse files Browse the repository at this point in the history
  • Loading branch information
Jerry Su committed Mar 18, 2015
0 parents commit ee5b454
Show file tree
Hide file tree
Showing 13 changed files with 517 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .gitignore
@@ -0,0 +1,28 @@
node_modules/*

node_modules/backbone/*
!node_modules/backbone/backbone.js

node_modules/backbone.localstorage/*
!node_modules/backbone.localstorage/backbone.localStorage.js

node_modules/jquery/*
!node_modules/jquery/dist
node_modules/jquery/dist/*
!node_modules/jquery/dist/jquery.js

node_modules/requirejs/*
!node_modules/requirejs/require.js

node_modules/requirejs-text/*
!node_modules/requirejs-text/text.js

node_modules/todomvc-app-css/*
!node_modules/todomvc-app-css/index.css

node_modules/todomvc-common/*
!node_modules/todomvc-common/base.css
!node_modules/todomvc-common/base.js

node_modules/underscore/*
!node_modules/underscore/underscore.js
30 changes: 30 additions & 0 deletions index.html
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en" data-framework="backbonejs">
<head>
<meta charset="utf-8">
<title>Backbone.js + RequireJS • TodoMVC</title>
<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
</head>
<body>
<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"></footer>
</section>
<footer 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>
<script src="node_modules/todomvc-common/base.js"></script>
<script data-main="js/main" src="node_modules/requirejs/require.js"></script>
</body>
</html>
38 changes: 38 additions & 0 deletions js/collections/todos.js
@@ -0,0 +1,38 @@
/*global define */
define([
'underscore',
'backbone',
'backboneLocalstorage',
'models/todo'
], function (_, Backbone, Store, Todo) {
'use strict';

var TodosCollection = 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.
completed: function () {
return this.where({completed: true});
},

// Filter down the list to only todo items that are still not finished.
remaining: function () {
return this.where({completed: false});
},

// 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 () {
return this.length ? this.last().get('order') + 1 : 1;
},

// Todos are sorted by their original insertion order.
comparator: 'order'
});

return new TodosCollection();
});
13 changes: 13 additions & 0 deletions js/common.js
@@ -0,0 +1,13 @@
/*global define*/
'use strict';

define([], function () {
return {
// Which filter are we using?
TodoFilter: '', // empty, active, completed

// What is the enter key constant?
ENTER_KEY: 13,
ESCAPE_KEY: 27
};
});
45 changes: 45 additions & 0 deletions js/main.js
@@ -0,0 +1,45 @@
/*global require*/
'use strict';

// Require.js allows us to configure shortcut alias
require.config({
// 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'
},
backboneLocalstorage: {
deps: ['backbone'],
exports: 'Store'
}
},
paths: {
jquery: '../node_modules/jquery/dist/jquery',
underscore: '../node_modules/underscore/underscore',
backbone: '../node_modules/backbone/backbone',
backboneLocalstorage: '../node_modules/backbone.localstorage/backbone.localStorage',
text: '../node_modules/requirejs-text/text'
}
});

require([
'backbone',
'views/app',
'routers/router'
], function (Backbone, AppView, Workspace) {
/*jshint nonew:false*/
// Initialize routing and start Backbone.history()
new Workspace();
Backbone.history.start();

// Initialize the application view
new AppView();
});
25 changes: 25 additions & 0 deletions js/models/todo.js
@@ -0,0 +1,25 @@
/*global define*/
define([
'underscore',
'backbone'
], function (_, Backbone) {
'use strict';

var Todo = Backbone.Model.extend({
// Default attributes for the todo
// and ensure that each todo created has `title` and `completed` keys.
defaults: {
title: '',
completed: false
},

// Toggle the `completed` state of this todo item.
toggle: function () {
this.save({
completed: !this.get('completed')
});
}
});

return Todo;
});
26 changes: 26 additions & 0 deletions js/routers/router.js
@@ -0,0 +1,26 @@
/*global define*/
define([
'jquery',
'backbone',
'collections/todos',
'common'
], function ($, Backbone, Todos, Common) {
'use strict';

var TodoRouter = Backbone.Router.extend({
routes: {
'*filter': 'setFilter'
},

setFilter: function (param) {
// Set the current filter to be used
Common.TodoFilter = param || '';

// Trigger a collection filter event, causing hiding/unhiding
// of the Todo view items
Todos.trigger('filter');
}
});

return TodoRouter;
});
15 changes: 15 additions & 0 deletions js/templates/stats.html
@@ -0,0 +1,15 @@
<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>
<% } %>
6 changes: 6 additions & 0 deletions js/templates/todos.html
@@ -0,0 +1,6 @@
<div class="view">
<input class="toggle" type="checkbox" <%= completed ? 'checked' : '' %>>
<label><%- title %></label>
<button class="destroy"></button>
</div>
<input class="edit" value="<%- title %>">
135 changes: 135 additions & 0 deletions js/views/app.js
@@ -0,0 +1,135 @@
/*global define*/
define([
'jquery',
'underscore',
'backbone',
'collections/todos',
'views/todos',
'text!templates/stats.html',
'common'
], function ($, _, Backbone, Todos, TodoView, statsTemplate, Common) {
'use strict';

// 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',

// Compile our stats template
template: _.template(statsTemplate),

// 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.allCheckbox = this.$('#toggle-all')[0];
this.$input = this.$('#new-todo');
this.$footer = this.$('#footer');
this.$main = this.$('#main');
this.$todoList = this.$('#todo-list');

this.listenTo(Todos, 'add', this.addOne);
this.listenTo(Todos, 'reset', this.addAll);
this.listenTo(Todos, 'change:completed', this.filterOne);
this.listenTo(Todos, 'filter', this.filterAll);
this.listenTo(Todos, 'all', this.render);

Todos.fetch({reset:true});
},

// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function () {
var completed = Todos.completed().length;
var remaining = Todos.remaining().length;

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;
},

// 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.$todoList.append(view.render().el);
},

// Add all items in the **Todos** collection at once.
addAll: function () {
this.$todoList.empty();
Todos.each(this.addOne, this);
},

filterOne: function (todo) {
todo.trigger('visible');
},

filterAll: function () {
Todos.each(this.filterOne, this);
},

// Generate the attributes for a new Todo item.
newAttributes: function () {
return {
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.which !== Common.ENTER_KEY || !this.$input.val().trim()) {
return;
}

Todos.create(this.newAttributes());
this.$input.val('');
},

// Clear all completed todo items, destroying their models.
clearCompleted: function () {
_.invoke(Todos.completed(), 'destroy');
return false;
},

toggleAllComplete: function () {
var completed = this.allCheckbox.checked;

Todos.each(function (todo) {
todo.save({
completed: completed
});
});
}
});

return AppView;
});

0 comments on commit ee5b454

Please sign in to comment.