-
Notifications
You must be signed in to change notification settings - Fork 0
/
value.js
69 lines (59 loc) · 1.86 KB
/
value.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
var value = function(data) {
var proxy;
var url;
var validationFunctions = {};
var validationErrors = [];
return {
get: function() {
return data;
},
set: function(val) {
if (_.isUndefined(val)) {
throw new Error('Error in value.set(): first argument shouldn\'t be undefined!')
}
if (this.validate(val)) {
data = val;
} else {
console.error(validationErrors);
}
return this;
},
proxy: function(config) {
url = config.url;
return this;
},
validations: function(list) {
_.each(list, function(name) {
validationFunctions[name] = validators[name];
});
return this;
},
validate: function(val) {
validationErrors = [];
_.each(validationFunctions, function(validator, name) {
if (!validator.call(this, val)) {
validationErrors.push(name);
}
});
return !validationErrors.length ? true : false;
},
fetch: function(callback, scope) {
if (!url) {
throw new Error('Error in value.fetch(): url should be specified!');
}
var that = this;
scope = !_.isUndefined(scope) ? scope : this;
$.get(url).success(function(val) {
that.set(val);
if (_.isFunction(callback)) {
callback.call(scope, val);
}
}).error(function(response) {
throw new Error(
'Error in value.fetch(): ' + response.status + ' ' + response.statusText + ' for ' + url
);
});
return this;
}
}
}