-
Notifications
You must be signed in to change notification settings - Fork 1
/
trapper.js
113 lines (110 loc) · 2.63 KB
/
trapper.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
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
(function(){
function Trapper(store){
if ($.isArray(store)){
return new ArrayTrapper(store);
} else if($.isPlainObject(store)) {
return new ObjectTrapper(store);
}
this.observers = [];
this.injest(store);
}
Trapper.prototype.set = function(path, value){
if (value === undefined) {value = path; path = null}
if (path && path.length) {
return this.resolve(path).set(value);
}
this.injest(value);
this.ping();
return this;
};
Trapper.prototype.get = function(path){
if (path) {
var resolved = this.resolve(path);
return resolved ? resolved.get() : undefined;
} else {
return this.flatten();
}
};
Trapper.prototype.injest = function(value){
this.store = value;
}
Trapper.prototype.flatten = function(){
return this.store;
}
Trapper.prototype.resolve = function(path){
if (!path || !path.length || path[0] === "") {
return this;
} else {
throw new Error("Path does not exist.");
}
};
Trapper.prototype.bind = function(observer, ping){
this.observers.push(observer);
var self = this;
if (ping) {
this.ping(observer);
};
return this;
};
Trapper.prototype.ping = function(callback){
value = this.get();
if (callback) {
callback.call(this, value);
} else {
var self = this;
$.each(this.observers, function(){
this.call(self, value);
});
}
}
function ObjectTrapper(store){
this.observers = [];
this.injest(store);
}
ObjectTrapper.prototype = new Trapper();
ObjectTrapper.prototype.resolve = function(path){
if (!path || !path.length || path[0] === "") {
return this;
} else if (!$.isArray(path)){
path = path.split('.');
}
var pathComponent = path.shift();
if (this.store[pathComponent]){
return this.store[pathComponent].resolve(path);
} else {
throw new Error("Key does not exist.");
}
}
ObjectTrapper.prototype.injest = function(value){
this.store = {};
for (var key in value){
this.store[key] = new Trapper(value[key]);
}
}
ObjectTrapper.prototype.flatten = function(){
var flattened = {};
for (var key in this.store){
flattened[key] = this.store[key].get();
}
return flattened;
}
function ArrayTrapper(store){
this.bindings = [];
this.injest(store);
}
ArrayTrapper.prototype = new ObjectTrapper();
ArrayTrapper.prototype.injest = function(value){
this.store = [];
for (var i = 0, length = value.length; i < length; i++){
this.store.push(new Trapper(value[i]));
}
}
ArrayTrapper.prototype.flatten = function(){
var flattened = [];
for (var i = 0, length = this.store.length; i < length; i++){
flattened.push(this.store[i].get());
}
return flattened;
};
window['Trapper'] = Trapper;
})();