-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataBinder.js
More file actions
68 lines (58 loc) · 1.65 KB
/
Copy pathDataBinder.js
File metadata and controls
68 lines (58 loc) · 1.65 KB
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
/*jshint -W054 */
define([], function(){
function Binder(model, containerElement) {
this.model = model;
this.containerElement = containerElement;
}
Binder.prototype.updateModelFromDOM = function() {
var ATTR_JSONPATH = "data-jsonpath";
var json = this.model;
var getControlValue = function() {
var type = control.getAttribute('type');
switch (control.tagName) {
case 'INPUT':
if (type === 'text' ||
type === 'password') {
return control.value;
} else if (type === 'checkbox') {
return control.checked;
}
break;
case 'TEXTAREA':
return control.value;
case 'SELECT':
return control.options[control.selectedIndex].value;
}
throw "Could not determine control type";
};
var setValue = function(jsonPath) {
var value = getControlValue(control);
control.modelType = control.modelType || getValueType(jsonPath);
if (control.modelType === "number") {
value = convertToNumber(jsonPath, value);
}
new Function(["json", "value"], "json." + jsonPath + " = value")(json, value);
};
var getValueType = function(jsonPath){
return typeof new Function(["json"], "return json." + jsonPath)(json);
};
var convertToNumber = function(jsonPath, newValue) {
var newValueNumber = parseFloat(newValue);
if (!isNaN(newValueNumber)) {
return newValueNumber;
}
return newValue;
};
var elements = this.containerElement.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
var control = elements[i];
var path = control.getAttribute(ATTR_JSONPATH);
if (path === null) {
continue;
}
setValue(path);
}
return this;
};
return Binder;
});