-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackbone.cache-amd.js
87 lines (83 loc) · 3.1 KB
/
backbone.cache-amd.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
define([
'jQuery',
'Backbone'
], function ($, Backbone) {
Backbone.Cache = function() {
this.store = {};
};
$.extend(Backbone.Cache.prototype, Backbone.Events, {
set: function(key, value) {
this.trigger("set", key, value);
this.store[key] = value;
},
has: function(key) {
var isHas = !!this.store[key];
this.trigger("has", key, isHas);
return isHas;
},
get: function(key) {
var value = this.store[key];
this.trigger("get", key, value);
return value;
},
remove: function(key) {
var value = this.store[key];
this.trigger("remove", key, value);
delete this.store[key];
return value;
},
clear: function() {
this.trigger("clear");
this.store = {};
}
});
Backbone.CachedCollection = Backbone.Collection.extend({
fetch: function(options) {
if (this.cacheKey && this.cacheObject) {
var cacheObject = this.cacheObject,
cacheKey = this.cacheKey;
if (cacheObject.has(cacheKey)) {
var resp = cacheObject.get(cacheKey),
method = options.update ? 'update' : 'reset';
this[method](resp, options);
if (options.success) options.success(this, resp, options);
return $.Deferred().resolve();
} else {
var success = options.success;
options.success = function(entity, resp, options) {
cacheObject.set(cacheKey, resp);
if (success) success(entity, resp, options);
};
return Backbone.Collection.prototype.fetch.call(this, options);
}
} else {
return Backbone.Collection.prototype.fetch.call(this, options);
}
}
});
Backbone.CachedModel = Backbone.Model.extend({
fetch: function(options) {
if (this.cacheKey && this.cacheObject) {
options = options || {};
var cacheObject = this.cacheObject,
cacheKey = this.cacheKey,
success = options.success;
if (cacheObject.has(cacheKey)) {
var resp = cacheObject.get(cacheKey);
this.set(this.parse(resp, options), options);
if (success) success(this, resp, options);
return $.Deferred().resolve();
} else {
options.success = function(entity, resp, options) {
cacheObject.set(cacheKey, resp);
if (success) success(entity, resp, options);
};
return Backbone.Model.prototype.fetch.call(this, options);
}
} else {
return Backbone.Model.prototype.fetch.call(this, options);
}
}
});
return Backbone;
});