Commit 8e20c96c authored by Sindre Sorhus's avatar Sindre Sorhus

Upgrade Backbone+RequireJS app to Backbone 0.9.9

- Update Backbone.localStorage and RequireJS
- Use `listenTo`
- Improve RequireJS config
parent 1a7c26ec
define([ define([
'underscore', 'underscore',
'backbone', 'backbone',
'lib/backbone/localstorage', 'backboneLocalstorage',
'models/todo' 'models/todo'
], function( _, Backbone, Store, Todo ) { ], function( _, Backbone, Store, Todo ) {
......
This diff is collapsed.
/**
* Backbone localStorage Adapter
* https://github.com/jeromegn/Backbone.localStorage
*/
(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) {
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) {
var store = model.localStorage || model.collection.localStorage;
var resp, syncDfd = $.Deferred && $.Deferred(); //If $ is having Deferred - use it.
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) {
if (options && options.success) options.success(resp);
if (syncDfd) syncDfd.resolve();
} else {
if (options && options.error) options.error("Record not found");
if (syncDfd) syncDfd.reject();
}
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]);
};
})(_, Backbone);
define(["underscore","backbone"],function(_,Backbone){function S4(){return((1+Math.random())*65536|0).toString(16).substring(1)}function guid(){return S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()}var Store=function(name){this.name=name;var store=localStorage.getItem(this.name);this.data=store&&JSON.parse(store)||{}};_.extend(Store.prototype,{save:function(){localStorage.setItem(this.name,JSON.stringify(this.data))},create:function(model){if(!model.id)model.id=model.attributes.id=guid();
this.data[model.id]=model;this.save();return model},update:function(model){this.data[model.id]=model;this.save();return model},find:function(model){return this.data[model.id]},findAll:function(){return _.values(this.data)},destroy:function(model){delete this.data[model.id];this.save();return model}});Backbone.sync=function(method,model,options){var resp;var store=model.localStorage||model.collection.localStorage;switch(method){case "read":resp=model.id?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")};return Store});
/** /**
* @license RequireJS text 2.0.1 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * @license RequireJS text 2.0.3 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license. * Available via the MIT or new BSD license.
* see: http://github.com/requirejs/text for details * see: http://github.com/requirejs/text for details
*/ */
...@@ -11,7 +11,8 @@ ...@@ -11,7 +11,8 @@
define(['module'], function (module) { define(['module'], function (module) {
'use strict'; 'use strict';
var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], var text, fs,
progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im, bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
hasLocation = typeof location !== 'undefined' && location.href, hasLocation = typeof location !== 'undefined' && location.href,
...@@ -19,11 +20,10 @@ define(['module'], function (module) { ...@@ -19,11 +20,10 @@ define(['module'], function (module) {
defaultHostName = hasLocation && location.hostname, defaultHostName = hasLocation && location.hostname,
defaultPort = hasLocation && (location.port || undefined), defaultPort = hasLocation && (location.port || undefined),
buildMap = [], buildMap = [],
masterConfig = (module.config && module.config()) || {}, masterConfig = (module.config && module.config()) || {};
text, fs;
text = { text = {
version: '2.0.1', version: '2.0.3',
strip: function (content) { strip: function (content) {
//Strips <?xml ...?> declarations so that external SVG and XML //Strips <?xml ...?> declarations so that external SVG and XML
...@@ -113,8 +113,8 @@ define(['module'], function (module) { ...@@ -113,8 +113,8 @@ define(['module'], function (module) {
* @returns Boolean * @returns Boolean
*/ */
useXhr: function (url, protocol, hostname, port) { useXhr: function (url, protocol, hostname, port) {
var match = text.xdRegExp.exec(url), var uProtocol, uHostName, uPort,
uProtocol, uHostName, uPort; match = text.xdRegExp.exec(url);
if (!match) { if (!match) {
return true; return true;
} }
...@@ -219,9 +219,10 @@ define(['module'], function (module) { ...@@ -219,9 +219,10 @@ define(['module'], function (module) {
} }
}; };
if (typeof process !== "undefined" && if (masterConfig.env === 'node' || (!masterConfig.env &&
process.versions && typeof process !== "undefined" &&
!!process.versions.node) { process.versions &&
!!process.versions.node)) {
//Using special require.nodeRequire, something added by r.js. //Using special require.nodeRequire, something added by r.js.
fs = require.nodeRequire('fs'); fs = require.nodeRequire('fs');
...@@ -233,7 +234,8 @@ define(['module'], function (module) { ...@@ -233,7 +234,8 @@ define(['module'], function (module) {
} }
callback(file); callback(file);
}; };
} else if (text.createXhr()) { } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
text.createXhr())) {
text.get = function (url, callback, errback) { text.get = function (url, callback, errback) {
var xhr = text.createXhr(); var xhr = text.createXhr();
xhr.open('GET', url, true); xhr.open('GET', url, true);
...@@ -261,14 +263,15 @@ define(['module'], function (module) { ...@@ -261,14 +263,15 @@ define(['module'], function (module) {
}; };
xhr.send(null); xhr.send(null);
}; };
} else if (typeof Packages !== 'undefined') { } else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
//Why Java, why is this so awkward? //Why Java, why is this so awkward?
text.get = function (url, callback) { text.get = function (url, callback) {
var encoding = "utf-8", var stringBuffer, line,
encoding = "utf-8",
file = new java.io.File(url), file = new java.io.File(url),
lineSeparator = java.lang.System.getProperty("line.separator"), lineSeparator = java.lang.System.getProperty("line.separator"),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
stringBuffer, line,
content = ''; content = '';
try { try {
stringBuffer = new java.lang.StringBuffer(); stringBuffer = new java.lang.StringBuffer();
......
...@@ -3,21 +3,26 @@ require.config({ ...@@ -3,21 +3,26 @@ require.config({
// The shim config allows us to configure dependencies for // The shim config allows us to configure dependencies for
// scripts that do not call define() to register a module // scripts that do not call define() to register a module
shim: { shim: {
'underscore': { underscore: {
exports: '_' exports: '_'
}, },
'backbone': { backbone: {
deps: [ deps: [
'underscore', 'underscore',
'jquery' 'jquery'
], ],
exports: 'Backbone' exports: 'Backbone'
},
backboneLocalstorage: {
deps: ['backbone'],
exports: 'Store'
} }
}, },
paths: { paths: {
jquery: 'lib/jquery/jquery.min', jquery: '../../../assets/jquery.min',
underscore: '../../../assets/lodash.min', underscore: '../../../assets/lodash.min',
backbone: 'lib/backbone/backbone', backbone: 'lib/backbone/backbone',
backboneLocalstorage: 'lib/backbone/backbone.localStorage',
text: 'lib/require/text' text: 'lib/require/text'
} }
}); });
......
...@@ -33,11 +33,11 @@ define([ ...@@ -33,11 +33,11 @@ define([
this.$footer = this.$('#footer'); this.$footer = this.$('#footer');
this.$main = this.$('#main'); this.$main = this.$('#main');
Todos.on( 'add', this.addOne, this ); this.listenTo(Todos, 'add', this.addOne);
Todos.on( 'reset', this.addAll, this ); this.listenTo(Todos, 'reset', this.addAll);
Todos.on( 'change:completed', this.filterOne, this ); this.listenTo(Todos, 'change:completed', this.filterOne);
Todos.on( "filter", this.filterAll, this); this.listenTo(Todos, 'filter', this.filterAll);
Todos.on( 'all', this.render, this ); this.listenTo(Todos, 'all', this.render);
Todos.fetch(); Todos.fetch();
}, },
......
...@@ -25,9 +25,9 @@ define([ ...@@ -25,9 +25,9 @@ define([
// 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.listenTo(this.model, 'change', this.render);
this.model.on( 'destroy', this.remove, this ); this.listenTo(this.model, 'destroy', this.remove);
this.model.on( 'visible', this.toggleVisible, this ); this.listenTo(this.model, 'visible', this.toggleVisible);
}, },
// Re-render the titles of the todo item. // Re-render the titles of the todo item.
......
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