-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backbone.uriSync.js
57 lines (52 loc) · 1.63 KB
/
Backbone.uriSync.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
!function(root){
function S4(){
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
var URI = {
parse: function() {
var hash = window.location.href.split("#")[1] || "",
json = decodeURIComponent(hash),
data = {};
try {
data = json ? JSON.parse(json) : {};
}
catch(e) {}
return data;
},
stringify: function(data) {
return encodeURIComponent(JSON.stringify(data));
}
};
root.uriSync = function(method, model, options) {
var resp = null,
data = URI.parse() || {};
switch (method) {
case "read":
resp = model.id ? data[model.id] || {} : data;
break;
case "create":
if (!model.id) {
model.set(model.idAttribute, guid());
}
resp = data[model.id] = model;
window.location.hash = URI.stringify(data);
break;
case "update":
resp = data[model.id] = model;
window.location.hash = URI.stringify(data);
break;
case "delete":
delete data[model.id];
window.location.hash = URI.stringify(data);
break;
}
if (resp) {
options.success(resp);
} else {
options.error("Record not found");
}
};
}(this);