Commit 45e8b94b authored by Stephen Sawchuk's avatar Stephen Sawchuk

Merge pull request #573 from stephenplusplus/bbm

backbone_marionette_require code style + spec comp.
parents 48b8ca7d ee9db311
app.build.js
js/main.built.js
js/lib/tpl.js
js/lib/backbone.js
js/lib/backbone.marionette.js
js/lib/backbone-localStorage.js
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
"dependencies": { "dependencies": {
"todomvc-common": "~0.1.6", "todomvc-common": "~0.1.6",
"requirejs": "~2.1.6", "requirejs": "~2.1.6",
"backbone.marionette": "~1.0.2" "underscore": "~1.4.4",
"backbone.marionette": "~1.0.3",
"backbone.localStorage": "~1.1.4"
} }
} }
/**
* Backbone localStorage Adapter
* Version 1.1.4
*
* https://github.com/jeromegn/Backbone.localStorage
*/
(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory(require("underscore"), require("backbone"));
} else if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["underscore","backbone"], function(_, Backbone) {
// Use global variables if the locals are undefined.
return factory(_ || root._, Backbone || root.Backbone);
});
} else {
// RequireJS isn't being used. Assume underscore and backbone are loaded in <script> tags
factory(_, Backbone);
}
}(this, function(_, Backbone) {
// 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
// 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) {
if( !this.localStorage ) {
throw "Backbone.localStorage: Environment does not support localStorage."
}
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 this.find(model);
},
// 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 this.find(model);
},
// Retrieve a model from `this.data` by id.
find: function(model) {
return this.jsonData(this.localStorage().getItem(this.name+"-"+model.id));
},
// Return the array of all models currently in storage.
findAll: function() {
// Lodash removed _#chain in v1.0.0-rc.1
return (_.chain || _)(this.records)
.map(function(id){
return this.jsonData(this.localStorage().getItem(this.name+"-"+id));
}, this)
.compact()
.value();
},
// Delete a model from `this.data`, returning it.
destroy: function(model) {
if (model.isNew())
return false
this.localStorage().removeItem(this.name+"-"+model.id);
this.records = _.reject(this.records, function(id){
return id === model.id.toString();
});
this.save();
return model;
},
localStorage: function() {
return localStorage;
},
// fix for "illegal access" error on Android when JSON.parse is passed null
jsonData: function (data) {
return data && JSON.parse(data);
},
// Clear localStorage for specific collection.
_clear: function() {
var local = this.localStorage(),
itemRe = new RegExp("^" + this.name + "-");
// Remove id-tracking item (e.g., "foo").
local.removeItem(this.name);
// Lodash removed _#chain in v1.0.0-rc.1
// Match all data items (e.g., "foo-ID") and remove.
(_.chain || _)(local).keys()
.filter(function (k) { return itemRe.test(k); })
.each(function (k) { local.removeItem(k); });
},
// Size of localStorage.
_storageSize: function() {
return this.localStorage().length;
}
});
// localSync delegate to the model or collection's
// *localStorage* property, which should be an instance of `Store`.
// window.Store.sync and Backbone.localSync is deprecated, use Backbone.LocalStorage.sync instead
Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
var store = model.localStorage || model.collection.localStorage;
var resp, errorMessage, syncDfd = Backbone.$.Deferred && Backbone.$.Deferred(); //If $ is having Deferred - use it.
try {
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;
}
} catch(error) {
if (error.code === DOMException.QUOTA_EXCEEDED_ERR && store._storageSize() === 0)
errorMessage = "Private browsing is unsupported";
else
errorMessage = error.message;
}
if (resp) {
if (options && options.success) {
if (Backbone.VERSION === "0.9.10") {
options.success(model, resp, options);
} else {
options.success(resp);
}
}
if (syncDfd) {
syncDfd.resolve(resp);
}
} else {
errorMessage = errorMessage ? errorMessage
: "Record Not Found";
if (options && options.error)
if (Backbone.VERSION === "0.9.10") {
options.error(model, errorMessage, options);
} else {
options.error(errorMessage);
}
if (syncDfd)
syncDfd.reject(errorMessage);
}
// add compatibility with $.ajax
// always execute callback for success and error
if (options && options.complete) options.complete(resp);
return syncDfd && syncDfd.promise();
};
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) {
return Backbone.getSyncMethod(model).apply(this, [method, model, options]);
};
return Backbone.LocalStorage;
}));
#todoapp.filter-active #todo-list .completed { #todoapp.filter-active #todo-list .completed,
display:none #todoapp.filter-completed #todo-list .active,
} #main,
#todoapp.filter-completed #todo-list .active { #footer {
display:none
}
#main, #footer {
display : none; display : none;
} }
<!doctype html>
<html lang="en" data-framework="marionettejs">
<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="bower_components/todomvc-common/base.css">
<link rel="stylesheet" href="css/custom.css">
</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="bower_components/todomvc-common/base.js"></script>
<script data-main="js/main" src="bower_components/requirejs/require.js"></script>
</body>
</html>
...@@ -19,9 +19,8 @@ ...@@ -19,9 +19,8 @@
<footer id="info"> <footer id="info">
<p>Double-click to edit a todo</p> <p>Double-click to edit a todo</p>
<p>Created by <a href="http://github.com/jsoverson">Jarrod Overson</a></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> </footer>
<script src="bower_components/todomvc-common/base.js"></script> <script src="bower_components/todomvc-common/base.js"></script>
<script data-main="js/main.built" src="bower_components/requirejs/require.js"></script> <script data-main="js/main" src="bower_components/requirejs/require.js"></script>
</body> </body>
</html> </html>
/*global $*/ /*global define */
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({ define([
header : '#header', 'marionette',
main : '#main', 'collections/TodoList',
footer : '#footer' 'views/Header',
}); 'views/TodoListCompositeView',
'views/Footer'
], function (Marionette, TodoList, Header, TodoListCompositeView, Footer) {
'use strict';
app.addInitializer(function(){ var app = new Marionette.Application();
var todoList = new TodoList();
var viewOptions = { var viewOptions = {
collection : todoList collection: todoList
}; };
app.header.show(new Header(viewOptions)); var header = new Header(viewOptions);
app.main.show(new TodoListCompositeView(viewOptions)); var main = new TodoListCompositeView(viewOptions);
app.footer.show(new Footer(viewOptions)); var footer = new Footer(viewOptions);
todoList.fetch(); app.addRegions({
header: '#header',
main: '#main',
footer: '#footer'
}); });
app.addInitializer(function () {
app.header.show(header);
app.main.show(main);
app.footer.show(footer);
vent.on('todoList:filter',function(filter) { todoList.fetch();
filter = filter || 'all'; });
$('#todoapp').attr('class', 'filter-' + filter);
app.listenTo(todoList, 'all', function () {
app.main.$el.toggle(todoList.length > 0);
app.footer.$el.toggle(todoList.length > 0);
}); });
vent.on('todoList:clear:completed',function(){ app.vent.on('todoList:filter', function (filter) {
function destroy(todo) { todo.destroy(); } footer.updateFilterSelection(filter);
todoList.getCompleted().forEach(destroy); document.getElementById('todoapp').className = 'filter-' + (filter === '' ? 'all' : filter);
}); });
return app; app.vent.on('todoList:clear:completed', function () {
todoList.getCompleted().forEach(function (todo) {
todo.destroy();
});
});
} return window.app = app;
); });
define(['backbone','models/Todo','lib/backbone-localStorage'],function(Backbone,Todo) { /*global define */
define([
'backbone',
'models/Todo',
'localStorage'
], function (Backbone, Todo) {
'use strict'; 'use strict';
function isCompleted(todo) { return todo.get('completed'); } function isCompleted(todo) {
return todo.get('completed');
}
return Backbone.Collection.extend({ return Backbone.Collection.extend({
model: Todo, model: Todo,
localStorage: new Backbone.LocalStorage('todos-backbone'), localStorage: new Backbone.LocalStorage('todos-backbone'),
getCompleted: function() { getCompleted: function () {
return this.filter(isCompleted); return this.filter(isCompleted);
}, },
getActive: function() {
getActive: function () {
return this.reject(isCompleted); return this.reject(isCompleted);
}, },
comparator: function( todo ) {
comparator: function (todo) {
return todo.get('created'); return todo.get('created');
} }
}); });
}); });
/*global define*/ /*global define */
define(['vent'], function (vent) { define([
"use strict"; 'app'
], function (app) {
'use strict';
return { return {
setFilter : function(param) { setFilter: function (param) {
vent.trigger('todoList:filter', param.trim() || ''); app.vent.trigger('todoList:filter', param && param.trim() || '');
} }
}; };
}); });
define(['marionette'],function(marionette) { /*global define */
define([
'marionette'
], function (Marionette) {
'use strict'; 'use strict';
return marionette.AppRouter.extend({ return Marionette.AppRouter.extend({
appRoutes:{ appRoutes: {
'*filter': 'setFilter' '*filter': 'setFilter'
} }
}); });
}); });
<span id="todo-count"><strong></strong> items left</span> <span id="todo-count"><strong>0</strong> items left</span>
<ul id="filters"> <ul id="filters">
<li> <li>
<a href="#/">All</a> <a href="#/">All</a>
...@@ -10,4 +10,4 @@ ...@@ -10,4 +10,4 @@
<a href="#/completed">Completed</a> <a href="#/completed">Completed</a>
</li> </li>
</ul> </ul>
<button id="clear-completed">Clear completed</button> <button id="clear-completed"></button>
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