Debian Codegraph @

examples/backbone.localStorage.js

raw
1 /**
2 * Backbone localStorage Adapter
3 * Version 1.1.0
4 *
5 * https://github.com/jeromegn/Backbone.localStorage
6 */
7 (function (root, factory) {
8 if (typeof define === "function" && define.amd) {
9 // AMD. Register as an anonymous module.
10 define(["underscore","backbone"], function(_, Backbone) {
11 // Use global variables if the locals are undefined.
12 return factory(_ || root._, Backbone || root.Backbone);
13 });
14 } else {
15 // RequireJS isn't being used. Assume underscore and backbone are loaded in script tags
16 factory(_, Backbone);
17 }
18 }(this, function(_, Backbone) {
19 // A simple module to replace `Backbone.sync` with *localStorage*-based
20 // persistence. Models are given GUIDS, and saved into a JSON object. Simple
21 // as that.
22
23 // Hold reference to Underscore.js and Backbone.js in the closure in order
24 // to make things work even if they are removed from the global namespace
25
26 // Generate four random hex digits.
27 function S4() {
28 return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
29 };
30
31 // Generate a pseudo-GUID by concatenating random hexadecimal.
32 function guid() {
33 return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
34 };
35
36 // Our Store is represented by a single JS object in *localStorage*. Create it
37 // with a meaningful name, like the name you'd give a table.
38 // window.Store is deprecated, use Backbone.LocalStorage instead
39 Backbone.LocalStorage = window.Store = function(name) {
40 this.name = name;
41 var store = this.localStorage().getItem(this.name);
42 this.records = (store && store.split(",")) || [];
43 };
44
45 _.extend(Backbone.LocalStorage.prototype, {
46
47 // Save the current state of the **Store** to *localStorage*.
48 save: function() {
49 this.localStorage().setItem(this.name, this.records.join(","));
50 },
51
52 // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
53 // have an id of it's own.
54 create: function(model) {
55 if (!model.id) {
56 model.id = guid();
57 model.set(model.idAttribute, model.id);
58 }
59 this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
60 this.records.push(model.id.toString());
61 this.save();
62 return this.find(model);
63 },
64
65 // Update a model by replacing its copy in `this.data`.
66 update: function(model) {
67 this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
68 if (!_.include(this.records, model.id.toString()))
69 this.records.push(model.id.toString()); this.save();
70 return this.find(model);
71 },
72
73 // Retrieve a model from `this.data` by id.
74 find: function(model) {
75 return this.jsonData(this.localStorage().getItem(this.name+"-"+model.id));
76 },
77
78 // Return the array of all models currently in storage.
79 findAll: function() {
80 return _(this.records).chain()
81 .map(function(id){
82 return this.jsonData(this.localStorage().getItem(this.name+"-"+id));
83 }, this)
84 .compact()
85 .value();
86 },
87
88 // Delete a model from `this.data`, returning it.
89 destroy: function(model) {
90 if (model.isNew())
91 return false
92 this.localStorage().removeItem(this.name+"-"+model.id);
93 this.records = _.reject(this.records, function(id){
94 return id === model.id.toString();
95 });
96 this.save();
97 return model;
98 },
99
100 localStorage: function() {
101 return localStorage;
102 },
103
104 // fix for "illegal access" error on Android when JSON.parse is passed null
105 jsonData: function (data) {
106 return data && JSON.parse(data);
107 }
108
109 });
110
111 // localSync delegate to the model or collection's
112 // *localStorage* property, which should be an instance of `Store`.
113 // window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead
114 Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
115 var store = model.localStorage || model.collection.localStorage;
116
117 var resp, errorMessage, syncDfd = $.Deferred && $.Deferred(); //If $ is having Deferred - use it.
118
119 try {
120
121 switch (method) {
122 case "read":
123 resp = model.id != undefined ? store.find(model) : store.findAll();
124 break;
125 case "create":
126 resp = store.create(model);
127 break;
128 case "update":
129 resp = store.update(model);
130 break;
131 case "delete":
132 resp = store.destroy(model);
133 break;
134 }
135
136 } catch(error) {
137 if (error.code === DOMException.QUOTA_EXCEEDED_ERR && window.localStorage.length === 0)
138 errorMessage = "Private browsing is unsupported";
139 else
140 errorMessage = error.message;
141 }
142
143 if (resp) {
144 model.trigger("sync", model, resp, options);
145 if (options && options.success)
146 options.success(resp);
147 if (syncDfd)
148 syncDfd.resolve(resp);
149
150 } else {
151 errorMessage = errorMessage ? errorMessage
152 : "Record Not Found";
153
154 if (options && options.error)
155 options.error(errorMessage);
156 if (syncDfd)
157 syncDfd.reject(errorMessage);
158 }
159
160 // add compatibility with $.ajax
161 // always execute callback for success and error
162 if (options && options.complete) options.complete(resp);
163
164 return syncDfd && syncDfd.promise();
165 };
166
167 Backbone.ajaxSync = Backbone.sync;
168
169 Backbone.getSyncMethod = function(model) {
170 if(model.localStorage || (model.collection && model.collection.localStorage)) {
171 return Backbone.localSync;
172 }
173
174 return Backbone.ajaxSync;
175 };
176
177 // Override 'Backbone.sync' to default to localSync,
178 // the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
179 Backbone.sync = function(method, model, options) {
180 return Backbone.getSyncMethod(model).apply(this, [method, model, options]);
181 };
182
183 return Backbone.LocalStorage;
184 }));