Commit 2a923887 authored by Jarrod Overson's avatar Jarrod Overson Committed by Sindre Sorhus

Backbone Marionette reference app

parent 4b44fafc
todomvc.com
\ No newline at end of file
js/lib/underscore.js
js/lib/backbone.js
js/lib/backbone.marionette.js
js/lib/backbone-localStorage.js
#todoapp.filter-active #todo-list .completed {
display:none
}
#todoapp.filter-completed #todo-list .active {
display:none
}
#main, #footer {
display : none;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Marionette • TodoMVC</title>
<link rel="stylesheet" href="../../../assets/base.css">
<link rel="stylesheet" href="css/custom.css">
<!--[if IE]>
<script src="../../../assets/ie.js"></script>
<![endif]-->
</head>
<body>
<section id="todoapp">
<header id="header"></header>
<section id="main"></section>
<footer id="footer"></footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://github.com/jsoverson">Jarrod Overson</a></p>
</footer>
<!-- vendor libraries -->
<script src="../../../assets/base.js"></script>
<script src="../../../assets/jquery.min.js"></script>
<script src="js/lib/underscore.js"></script>
<script src="js/lib/backbone.js"></script>
<script src="js/lib/backbone-localStorage.js"></script>
<script src="js/lib/backbone.marionette.js"></script>
<!-- application libraries -->
<script src="js/models/Todo.js"></script>
<script src="js/collections/TodoList.js"></script>
<script src="js/Router.js"></script>
<!-- application views -->
<script src="js/views/Footer.js"></script>
<script src="js/views/Header.js"></script>
<script src="js/views/TodoItemView.js"></script>
<script src="js/views/TodoListCompositeView.js"></script>
<!-- application -->
<script src="js/app.js"></script>
<script type="text/html" id="template-footer">
<span id="todo-count"><strong></strong> items left</span>
<ul id="filters">
<li>
<a href="#/">All</a>
</li>
<li>
<a href="#/active">Active</a>
</li>
<li>
<a href="#/completed">Completed</a>
</li>
</ul>
<button id="clear-completed">Clear completed</button>
</script>
<script type="text/html" id="template-header">
<h1>todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
</script>
<script type="text/html" id="template-todoItemView">
<div class="view">
<input class="toggle" type="checkbox" <% if (completed) { %>checked<% } %>>
<label><%= title %></label>
<button class="destroy"></button>
</div>
<input class="edit" value="<%= title %>">
</script>
<script type="text/html" id="template-todoListCompositeView">
<input id="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list"></ul>
</script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22728809-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
var Router = Backbone.Marionette.AppRouter.extend({
appRoutes : {
'*filter': 'setFilter'
},
controller : {
setFilter : function(param) {
app.vent.trigger('todoList:filter', param.trim() || '');
}
}
});
/*global $*/
var todoList = new TodoList();
var app = new Backbone.Marionette.Application();
app.bindTo(todoList, 'all', function () {
if (todoList.length === 0) {
app.main.$el.hide();
app.footer.$el.hide();
} else {
app.main.$el.show();
app.footer.$el.show();
}
});
app.addRegions({
header : '#header',
main : '#main',
footer : '#footer'
});
app.addInitializer(function(){
app.header.show(new Header());
app.main.show(new TodoListCompositeView({
collection : todoList
}));
app.footer.show(new Footer());
todoList.fetch();
});
app.vent.on('todoList:filter',function(filter) {
filter = filter || 'all';
$('#todoapp').attr('class', 'filter-' + filter);
});
$(function(){
app.start();
new Router();
Backbone.history.start();
});
var TodoList = (function(){
function isCompleted(todo) { return todo.get('completed'); }
return Backbone.Collection.extend({
model: Todo,
localStorage: new Backbone.LocalStorage('todos-backbone'),
getCompleted: function() {
return this.filter(isCompleted);
},
getActive: function() {
return this.reject(isCompleted);
},
comparator: function( todo ) {
return todo.get('created');
}
});
}());
/**
* Backbone localStorage Adapter
* https://github.com/jeromegn/Backbone.localStorage
*/
(function() {
// A simple module to replace `Backbone.sync` with *localStorage*-based
// persistence. Models are given GUIDS, and saved into a JSON object. Simple
// as that.
// Hold reference to Underscore.js and Backbone.js in the closure in order
// to make things work even if they are removed from the global namespace
var _ = this._;
var Backbone = this.Backbone;
// Generate four random hex digits.
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
// Our Store is represented by a single JS object in *localStorage*. Create it
// with a meaningful name, like the name you'd give a table.
// window.Store is deprectated, use Backbone.LocalStorage instead
Backbone.LocalStorage = window.Store = function(name) {
this.name = name;
var store = this.localStorage().getItem(this.name);
this.records = (store && store.split(",")) || [];
};
_.extend(Backbone.LocalStorage.prototype, {
// Save the current state of the **Store** to *localStorage*.
save: function() {
this.localStorage().setItem(this.name, this.records.join(","));
},
// Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
// have an id of it's own.
create: function(model) {
if (!model.id) {
model.id = guid();
model.set(model.idAttribute, model.id);
}
this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
this.records.push(model.id.toString());
this.save();
return model.toJSON();
},
// Update a model by replacing its copy in `this.data`.
update: function(model) {
this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save();
return model.toJSON();
},
// Retrieve a model from `this.data` by id.
find: function(model) {
return JSON.parse(this.localStorage().getItem(this.name+"-"+model.id));
},
// Return the array of all models currently in storage.
findAll: function() {
return _(this.records).chain()
.map(function(id){return JSON.parse(this.localStorage().getItem(this.name+"-"+id));}, this)
.compact()
.value();
},
// Delete a model from `this.data`, returning it.
destroy: function(model) {
this.localStorage().removeItem(this.name+"-"+model.id);
this.records = _.reject(this.records, function(record_id){return record_id == model.id.toString();});
this.save();
return model;
},
localStorage: function() {
return localStorage;
}
});
// localSync delegate to the model or collection's
// *localStorage* property, which should be an instance of `Store`.
// window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead
Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options, error) {
var store = model.localStorage || model.collection.localStorage;
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
options = {
success: options,
error: error
};
}
var resp;
switch (method) {
case "read": resp = model.id != undefined ? store.find(model) : store.findAll(); break;
case "create": resp = store.create(model); break;
case "update": resp = store.update(model); break;
case "delete": resp = store.destroy(model); break;
}
if (resp) {
options.success(resp);
} else {
options.error("Record not found");
}
};
Backbone.ajaxSync = Backbone.sync;
Backbone.getSyncMethod = function(model) {
if(model.localStorage || (model.collection && model.collection.localStorage))
{
return Backbone.localSync;
}
return Backbone.ajaxSync;
};
// Override 'Backbone.sync' to default to localSync,
// the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
Backbone.sync = function(method, model, options, error) {
return Backbone.getSyncMethod(model).apply(this, [method, model, options, error]);
};
})();
var Todo = Backbone.Model.extend({
localStorage: new Backbone.LocalStorage('todos-backbone'),
defaults: {
title : '',
completed : false,
created : 0
},
initialize : function() {
if (this.isNew()) this.set('created', Date.now());
},
toggle : function() {
return this.set('completed', !this.get('completed'));
}
});
var Footer = Backbone.Marionette.Layout.extend({
template : "#template-footer",
ui : {
count : '#todo-count strong',
filters : '#filters a'
},
events : {
'click #clear-completed' : 'onClearClick'
},
initialize : function() {
this.bindTo(app.vent, 'todoList:filter', this.updateFilterSelection, this);
this.bindTo(todoList, 'all', this.updateCount, this);
},
onRender : function() {
this.updateCount();
},
updateCount : function() {
this.ui.count.html(todoList.getActive().length);
},
updateFilterSelection : function(filter) {
this.ui.filters.removeClass('selected').filter('[href="#/' + filter + '"]').addClass('selected');
},
onClearClick : function() {
function destroy(todo) { todo.destroy(); }
todoList.getCompleted().forEach(destroy);
}
});
var Header = Backbone.Marionette.ItemView.extend({
template : "#template-header",
ui : {
input : '#new-todo'
},
events : {
'keypress #new-todo': 'onInputKeypress'
},
onInputKeypress : function(evt) {
var ENTER_KEY = 13;
var todoText = this.ui.input.val().trim();
if ( evt.which === ENTER_KEY && todoText ) {
todoList.create({
title : todoText
});
this.ui.input.val('');
}
}
});
var TodoItemView = Backbone.Marionette.CompositeView.extend({
tagName : 'li',
template : "#template-todoItemView",
ui : {
edit : '.edit'
},
events : {
'click .destroy' : 'destroy',
'dblclick label' : 'onEditClick',
'keypress .edit' : 'onEditKeypress',
'click .toggle' : 'toggle'
},
initialize : function() {
this.bindTo(this.model, 'change', this.render, this);
},
onRender : function() {
this.$el.removeClass('active completed');
if (this.model.get('completed')) this.$el.addClass('completed');
else this.$el.addClass('active');
},
destroy : function() {
this.model.destroy();
},
toggle : function() {
this.model.toggle().save();
},
onEditClick : function() {
this.$el.addClass('editing');
this.ui.edit.focus();
},
onEditKeypress : function(evt) {
var ENTER_KEY = 13;
var todoText = this.ui.edit.val().trim();
if ( evt.which === ENTER_KEY && todoText ) {
this.model.set('title', todoText).save();
this.$el.removeClass('editing');
}
}
});
var TodoListCompositeView = Backbone.Marionette.CompositeView.extend({
template : "#template-todoListCompositeView",
itemView : TodoItemView,
itemViewContainer : '#todo-list',
ui : {
toggle : '#toggle-all'
},
events : {
'click #toggle-all' : 'onToggleAllClick'
},
initialize : function() {
this.bindTo(this.collection, 'all', this.updateToggleCheckbox, this);
},
onRender : function() {
this.updateToggleCheckbox();
},
updateToggleCheckbox : function() {
function reduceCompleted(left, right) { return left && right.get('completed'); }
var allCompleted = this.collection.reduce(reduceCompleted,true);
this.ui.toggle.prop('checked', allCompleted);
},
onToggleAllClick : function(evt) {
var isChecked = evt.currentTarget.checked;
this.collection.each(function(todo){
todo.save({'completed': isChecked});
});
}
});
app.build.js
r.js
js/main.built.js
js/lib/underscore.js
js/lib/tpl.js
js/lib/backbone.js
js/lib/backbone.marionette.js
js/lib/backbone-localStorage.js
js/lib/require.js
({
baseUrl: "js/",
mainConfigFile: 'js/main.js',
out: "js/main.built.js",
include : 'main',
optimize: "uglify",
uglify: {
toplevel: true,
ascii_only: true,
beautify: false,
max_line_length: 1000
},
inlineText: true,
useStrict: false,
skipPragmas: false,
skipModuleInsertion: false,
stubModules: ['text'],
optimizeAllPluginResources: false,
findNestedDependencies: false,
removeCombined: false,
fileExclusionRegExp: /^\./,
preserveLicenseComments: true,
logLevel: 0
})
#todoapp.filter-active #todo-list .completed {
display:none
}
#todoapp.filter-completed #todo-list .active {
display:none
}
#main, #footer {
display : none;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Backbone.Marionette & Requirejs • TodoMVC</title>
<link rel="stylesheet" href="../../../assets/base.css">
<link rel="stylesheet" href="css/custom.css">
<!--[if IE]>
<script src="../../../assets/ie.js"></script>
<![endif]-->
</head>
<body>
<section id="todoapp">
<header id="header">
</header>
<section id="main">
</section>
<footer id="footer">
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://github.com/jsoverson">Jarrod Overson</a></p>
<p><a href="./index.html">View the built version</a></p>
</footer>
<script src="../../../assets/base.js"></script>
<script data-main="js/main" src="js/lib/require.js"></script>
<script>
var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-22728809-1']);_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Backbone.Marionette & Requirejs • TodoMVC</title>
<link rel="stylesheet" href="../../../assets/base.css">
<link rel="stylesheet" href="css/custom.css">
<!--[if IE]>
<script src="../../../assets/ie.js"></script>
<![endif]-->
</head>
<body>
<section id="todoapp">
<header id="header">
</header>
<section id="main">
</section>
<footer id="footer">
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://github.com/jsoverson">Jarrod Overson</a></p>
<p><a href="./index-dev.html">View the unbuilt version</a></p>
</footer>
<script src="../../../assets/base.js"></script>
<script data-main="js/main.built" src="js/lib/require.js"></script>
<script>
var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-22728809-1']);_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
/*global $*/
define(
['marionette','vent','collections/TodoList','views/Header','views/TodoListCompositeView','views/Footer'],
function(marionette, vent, TodoList, Header, TodoListCompositeView, Footer){
"use strict";
var app = new marionette.Application(),
todoList = new TodoList();
app.bindTo(todoList, 'all', function() {
if (todoList.length === 0) {
app.main.$el.hide();
app.footer.$el.hide();
} else {
app.main.$el.show();
app.footer.$el.show();
}
});
app.addRegions({
header : '#header',
main : '#main',
footer : '#footer'
});
app.addInitializer(function(){
var viewOptions = {
collection : todoList
};
app.header.show(new Header(viewOptions));
app.main.show(new TodoListCompositeView(viewOptions));
app.footer.show(new Footer(viewOptions));
todoList.fetch();
});
vent.on('todoList:filter',function(filter) {
filter = filter || 'all';
$('#todoapp').attr('class', 'filter-' + filter);
});
vent.on('todoList:clear:completed',function(){
function destroy(todo) { todo.destroy(); }
todoList.getCompleted().forEach(destroy);
});
return app;
}
);
define(['backbone','models/Todo','lib/backbone-localStorage'],function(Backbone,Todo) {
'use strict';
function isCompleted(todo) { return todo.get('completed'); }
return Backbone.Collection.extend({
model: Todo,
localStorage: new Backbone.LocalStorage('todos-backbone'),
getCompleted: function() {
return this.filter(isCompleted);
},
getActive: function() {
return this.reject(isCompleted);
},
comparator: function( todo ) {
return todo.get('created');
}
});
});
/*global define*/
define(['vent'], function (vent) {
"use strict";
return {
setFilter : function(param) {
vent.trigger('todoList:filter', param.trim() || '');
}
};
});
/**
* Backbone localStorage Adapter
* https://github.com/jeromegn/Backbone.localStorage
*/
(function() {
// A simple module to replace `Backbone.sync` with *localStorage*-based
// persistence. Models are given GUIDS, and saved into a JSON object. Simple
// as that.
// Hold reference to Underscore.js and Backbone.js in the closure in order
// to make things work even if they are removed from the global namespace
var _ = this._;
var Backbone = this.Backbone;
// Generate four random hex digits.
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
// Our Store is represented by a single JS object in *localStorage*. Create it
// with a meaningful name, like the name you'd give a table.
// window.Store is deprectated, use Backbone.LocalStorage instead
Backbone.LocalStorage = window.Store = function(name) {
this.name = name;
var store = this.localStorage().getItem(this.name);
this.records = (store && store.split(",")) || [];
};
_.extend(Backbone.LocalStorage.prototype, {
// Save the current state of the **Store** to *localStorage*.
save: function() {
this.localStorage().setItem(this.name, this.records.join(","));
},
// Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
// have an id of it's own.
create: function(model) {
if (!model.id) {
model.id = guid();
model.set(model.idAttribute, model.id);
}
this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
this.records.push(model.id.toString());
this.save();
return model.toJSON();
},
// Update a model by replacing its copy in `this.data`.
update: function(model) {
this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save();
return model.toJSON();
},
// Retrieve a model from `this.data` by id.
find: function(model) {
return JSON.parse(this.localStorage().getItem(this.name+"-"+model.id));
},
// Return the array of all models currently in storage.
findAll: function() {
return _(this.records).chain()
.map(function(id){return JSON.parse(this.localStorage().getItem(this.name+"-"+id));}, this)
.compact()
.value();
},
// Delete a model from `this.data`, returning it.
destroy: function(model) {
this.localStorage().removeItem(this.name+"-"+model.id);
this.records = _.reject(this.records, function(record_id){return record_id == model.id.toString();});
this.save();
return model;
},
localStorage: function() {
return localStorage;
}
});
// localSync delegate to the model or collection's
// *localStorage* property, which should be an instance of `Store`.
// window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead
Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options, error) {
var store = model.localStorage || model.collection.localStorage;
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
options = {
success: options,
error: error
};
}
var resp;
switch (method) {
case "read": resp = model.id != undefined ? store.find(model) : store.findAll(); break;
case "create": resp = store.create(model); break;
case "update": resp = store.update(model); break;
case "delete": resp = store.destroy(model); break;
}
if (resp) {
options.success(resp);
} else {
options.error("Record not found");
}
};
Backbone.ajaxSync = Backbone.sync;
Backbone.getSyncMethod = function(model) {
if(model.localStorage || (model.collection && model.collection.localStorage))
{
return Backbone.localSync;
}
return Backbone.ajaxSync;
};
// Override 'Backbone.sync' to default to localSync,
// the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
Backbone.sync = function(method, model, options, error) {
return Backbone.getSyncMethod(model).apply(this, [method, model, options, error]);
};
})();
/**
* Adapted from the official plugin text.js
*
* Uses UnderscoreJS micro-templates : http://documentcloud.github.com/underscore/#template
* @author Julien Cabanès <julien@zeeagency.com>
* @version 0.2
*
* @license RequireJS text 0.24.0 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
/*jslint regexp: false, nomen: false, plusplus: false, strict: false */
/*global require: false, XMLHttpRequest: false, ActiveXObject: false,
define: false, window: false, process: false, Packages: false,
java: false */
(function () {
//>>excludeStart('excludeTpl', pragmas.excludeTpl)
var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
buildMap = [],
templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g
},
/**
* JavaScript micro-templating, similar to John Resig's implementation.
* Underscore templating handles arbitrary delimiters, preserves whitespace,
* and correctly escapes quotes within interpolated code.
*/
template = function(str, data) {
var c = templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "; __p.push('";
})
.replace(/\r/g, '')
.replace(/\n/g, '')
.replace(/\t/g, '')
+ "');}return __p.join('');";
return tmpl;
/** /
var func = new Function('obj', tmpl);
return data ? func(data) : func;
/**/
};
//>>excludeEnd('excludeTpl')
define(function () {
//>>excludeStart('excludeTpl', pragmas.excludeTpl)
var tpl;
var get, fs;
if (typeof window !== "undefined" && window.navigator && window.document) {
get = function (url, callback) {
var xhr = tpl.createXhr();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (evt) {
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
};
} else if (typeof process !== "undefined" &&
process.versions &&
!!process.versions.node) {
//Using special require.nodeRequire, something added by r.js.
fs = require.nodeRequire('fs');
get = function (url, callback) {
callback(fs.readFileSync(url, 'utf8'));
};
}
return tpl = {
version: '0.24.0',
strip: function (content) {
//Strips <?xml ...?> declarations so that external SVG and XML
//documents can be added to a document without worry. Also, if the string
//is an HTML document, only the part inside the body tag is returned.
if (content) {
content = content.replace(xmlRegExp, "");
var matches = content.match(bodyRegExp);
if (matches) {
content = matches[1];
}
} else {
content = "";
}
return content;
},
jsEscape: function (content) {
return content.replace(/(['\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "")
.replace(/[\t]/g, "")
.replace(/[\r]/g, "");
},
createXhr: function () {
//Would love to dump the ActiveX crap in here. Need IE 6 to die first.
var xhr, i, progId;
if (typeof XMLHttpRequest !== "undefined") {
return new XMLHttpRequest();
} else {
for (i = 0; i < 3; i++) {
progId = progIds[i];
try {
xhr = new ActiveXObject(progId);
} catch (e) {}
if (xhr) {
progIds = [progId]; // so faster next time
break;
}
}
}
if (!xhr) {
throw new Error("require.getXhr(): XMLHttpRequest not available");
}
return xhr;
},
get: get,
load: function (name, req, onLoad, config) {
//Name has format: some.module.filext!strip
//The strip part is optional.
//if strip is present, then that means only get the string contents
//inside a body tag in an HTML string. For XML/SVG content it means
//removing the <?xml ...?> declarations so the content can be inserted
//into the current doc without problems.
var strip = false, url, index = name.indexOf("."),
modName = name.substring(0, index),
ext = name.substring(index + 1, name.length);
index = ext.indexOf("!");
if (index !== -1) {
//Pull off the strip arg.
strip = ext.substring(index + 1, ext.length);
strip = strip === "strip";
ext = ext.substring(0, index);
}
//Load the tpl.
url = 'nameToUrl' in req ? req.nameToUrl(modName, "." + ext) : req.toUrl(modName + "." + ext);
tpl.get(url, function (content) {
content = template(content);
if(!config.isBuild) {
//if(typeof window !== "undefined" && window.navigator && window.document) {
content = new Function('obj', content);
}
content = strip ? tpl.strip(content) : content;
if (config.isBuild && config.inlineText) {
buildMap[name] = content;
}
onLoad(content);
});
},
write: function (pluginName, moduleName, write) {
if (moduleName in buildMap) {
var content = tpl.jsEscape(buildMap[moduleName]);
write("define('" + pluginName + "!" + moduleName +
"', function() {return function(obj) { " +
content.replace(/(\\')/g, "'").replace(/(\\\\)/g, "\\")+
"}});\n");
}
}
};
//>>excludeEnd('excludeTpl')
return function() {};
});
//>>excludeEnd('excludeTpl')
}());
require.config({
paths : {
underscore : 'lib/underscore',
backbone : 'lib/backbone',
marionette : 'lib/backbone.marionette',
jquery : '../../../../assets/jquery.min',
tpl : 'lib/tpl'
},
shim : {
'lib/backbone-localStorage' : ['backbone'],
underscore : {
exports : '_'
},
backbone : {
exports : 'Backbone',
deps : ['jquery','underscore']
},
marionette : {
exports : 'Backbone.Marionette',
deps : ['backbone']
}
},
deps : ['jquery','underscore']
});
require(['app','backbone','routers/index','controllers/index'],function(app,Backbone,Router,Controller){
"use strict";
app.start();
new Router({
controller : Controller
});
Backbone.history.start();
});
define(['backbone','lib/backbone-localStorage'],function(Backbone){
'use strict';
return Backbone.Model.extend({
localStorage: new Backbone.LocalStorage('todos-backbone'),
defaults: {
title : '',
completed : false,
created : 0
},
initialize : function() {
if (this.isNew()) this.set('created', Date.now());
},
toggle : function() {
return this.set('completed', !this.get('completed'));
}
});
});
define(['marionette'],function(marionette) {
'use strict';
return marionette.AppRouter.extend({
appRoutes:{
'*filter': 'setFilter'
}
});
});
define(function(require){
"use strict";
return {
todoItemView : require('tpl!templates/todoItemView.tmpl'),
todosCompositeView : require('tpl!templates/todoListCompositeView.tmpl'),
footer : require('tpl!templates/footer.tmpl'),
header : require('tpl!templates/header.tmpl')
};
});
<span id="todo-count"><strong></strong> items left</span>
<ul id="filters">
<li>
<a href="#/">All</a>
</li>
<li>
<a href="#/active">Active</a>
</li>
<li>
<a href="#/completed">Completed</a>
</li>
</ul>
<button id="clear-completed">Clear completed</button>
<h1>todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
<div class="view">
<input class="toggle" type="checkbox" <% if (completed) { %>checked<% } %>>
<label><%= title %></label>
<button class="destroy"></button>
</div>
<input class="edit" value="<%= title %>">
This diff is collapsed.
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