-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbackbone.safe.js
More file actions
238 lines (199 loc) · 5.95 KB
/
Copy pathbackbone.safe.js
File metadata and controls
238 lines (199 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/**
* Safe - support for storing Backbone.Model to localstorage
* using the 'set' method of Model
*
* @constructor - use the key 'safe' to define unique storage key for backbone safe
*
* examples:
*
* // simple defintion for safe
* Backbone.Model.extend({ key: 'my-unique-key' });
*
* // advanced defintion for safe with options
* Backbone.Model.extend({
*
* safe: {
* key: 'my-unique-key',
* options: {
* reload: true
* }
* }
*
* })
*
* @requires Backbone.js, Underscore.js
* @param {string} uniqueID - the name of the storage you'de like to use
* @param {object} context - the Backbone.Model instance reference
* @param {object} options - (optional) configuration for setting up various features
* - {boolean} reload - true to reload (before initialize) data from local sotrage if exists
*
* @author Oren Farhi, http://orizens.com
*
* @version 0.3
*
*/
(function(){
var _ = this._;
var Backbone = this.Backbone;
// if Underscore or Backbone have not been loaded
// exit to prevent js errors
if (!_ || !Backbone || !JSON) {
return;
}
// factory for creating extend replacement for Backbone Objects
function BackboneExtender(bbObject, plugins) {
var thisExtender = this;
this.plugins = plugins;
bbObject["extend"] = _.wrap(bbObject["extend"], function(sourceExtend, config){
config = config || {}
// thisExtender.config = config;
var _sourceFn = config.initialize || this.prototype.initialize || function(){};
config.initialize = function(){
var args = [].slice.call(arguments);
thisExtender.config = config;
thisExtender.applyPlugins(this, args);
_sourceFn.apply(this, args);
};
return sourceExtend.call(this, config);
});
};
BackboneExtender.prototype.applyPlugins = function(instance, args) {
var config = this.config,
plugins = this.plugins,
args = args || [];
// run the plugins on this
_.each(plugins, function(plugFn){
plugFn.call(instance, config, args);
});
};
BackboneExtender.prototype.addPlug = function(plugFn) {
this.plugins.push(plugFn);
};
var SafePlug = function (config, args) {
var storageKey;
// create safe if exist as key
if (config && config.safe) {
// handle key, value safe
storageKey = config.safe.key ? config.safe.key : config.safe;
Backbone.Safe.create(storageKey, this, config.safe.options || { reload: true });
}
}
// extend Model & Collection constructor to handle safe initialization
// Backbone.Model.extend = _.wrap(Backbone.Model.extend, BackboneExtender)
var modelSafePlugin = new BackboneExtender(Backbone.Model, [ SafePlug ]);
var collectionSafePlugin = new BackboneExtender(Backbone.Collection, [ SafePlug ]);
Backbone.Safe = function(uniqueID, context, options) {
// parsing options settings
this._reload = options && options.reload && options.reload === true;
this.uid = uniqueID;
this.context = context;
this.isCollection = context.models && context.add;
// mixins for collection and model
var collection = {
// events that Safe is listening in order to
// trigger save to local storage
events: 'add reset change sort',
// the value to be used when cleaning the safe
emptyValue: '[]',
reload: function() {
context.add(this.getData());
},
fetch: function(options) {
var fetchFromSafe = options && options.from;
if (fetchFromSafe && fetchFromSafe === "safe") {
this.safe.reload();
} else {
Backbone.Collection.prototype.fetch.apply(this, arguments);
}
},
toJSON: function(model) {
return model.collection.toJSON();
}
};
var model = {
events: 'change',
emptyValue: '{}',
reload: function() {
context.set(this.getData());
},
// options = { from: "safe" }
fetch: function (options) {
var fetchFromSafe = options && options.from;
if (fetchFromSafe && fetchFromSafe === "safe") {
this.safe.reload();
} else {
Backbone.Model.prototype.fetch.apply(this, arguments);
}
},
toJSON: function(model) {
return model.toJSON();
}
};
// attach relevant object to Safe prototype
_.extend( this, this.isCollection ? collection : model );
// if the uid doesn't exist, create it
this.ensureUID();
// These are the lines that are responsible for
// loading the saved data from the local storage to the model
//
// the data is loaded before the Safe binds to change events
// storage exist ? -> save to model
// if it's a collection - use add
if (this._reload) {
this.reload();
}
// attach Backbone custom methods
_.extend(context, _.pick(this, ['fetch']));
// listen to any change event and cache it
context.on(this.events, this.store, this);
// adding destroy handler
context.on('destroy', this.destroy, this);
};
Backbone.Safe.prototype = {
/**
* creates a local storage item with the provided
* UID if not exist
*/
ensureUID: function() {
if (_.isNull(this.getData())){
this.create();
}
},
create: function() {
this.storage().setItem(this.uid, this.emptyValue);
},
/*
* @bbDataObj {collection/model}
*/
store: function(bbDataObj) {
this.storage()
.setItem(this.uid, JSON.stringify( this.toJSON( bbDataObj )));
},
storage: function() {
return localStorage;
},
/**
* returns json object of the local saved data
* @return {json}
*/
getData: function() {
// JSON.parse can't be run with an empty string
this._current = this.storage().getItem(this.uid);
return this._current ? JSON.parse(this._current) : this._current;
},
// set the local storage key to the empty value
reset: function() {
this.create();
},
// removes the key from the localstorage
destroy: function() {
this.storage().removeItem( this.uid );
}
};
// factory method
Backbone.Safe.create = function( uniqueID, context, options) {
if (uniqueID && context) {
context.safe = new Backbone.Safe(uniqueID, context, options);
}
};
})();