-
Notifications
You must be signed in to change notification settings - Fork 4
/
backbone-session.js
66 lines (66 loc) · 1.95 KB
/
backbone-session.js
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
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
} else {
root.BackboneSession = factory(root._, root.Backbone);
}
}(this, function(_, Backbone) {
return Backbone.Model.extend({
url: function() {
return 'Backbone.Session';
},
initialize: function(properties, options) {
this.options = options || {};
},
destroy: function(options) {
return this.sync('delete', this, options);
},
sync: function(method, model, options) {
options = options || {};
var url = model.options.url || model.url;
var key = _.isFunction(url) ? url() : '' + url;
var response;
switch (method) {
case 'create':
case 'update':
var data = model.toJSON();
var text = JSON.stringify(data);
response = localStorage.setItem(key, text);
break;
case 'delete':
response = localStorage.removeItem(key);
break;
case 'read':
response = JSON.parse(localStorage.getItem(key));
break;
}
if (_.isFunction(options.success)) {
options.success(response);
}
return Backbone.$.Deferred()
.resolve(response)
.promise();
},
signIn: function(options) {
return Backbone.$.Deferred()
.reject(Error('Override the signIn method'))
.promise();
},
signOut: function(options) {
options = options || {};
this.destroy();
this.clear();
this.trigger('signOut');
return Backbone.$.Deferred().resolve().promise();
},
getAuthStatus: function(options) {
return Backbone.$.Deferred()
.reject(Error('Override the getAuthStatus method'))
.promise();
},
Model: Backbone.Model,
Collection: Backbone.Collection
});
}));