-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaja.js
86 lines (81 loc) · 2.32 KB
/
aja.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
if(!AJAMU) {
var AJAMU = {};
}
if(!String.prototype.escapeRegExp) {
String.prototype.escapeRegExp = function() {
return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
}
AJAMU.initialize = function() {
var ajas = document.querySelectorAll("aja");
for(var i=ajas.length-1; i>=0; --i) {
AJAMU.request({aja: ajas[i]});
}
};
AJAMU.request = function(spec) {
var aja = spec.aja;
aja.style.display = "none";
var src = aja.getAttribute("src");
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === 4) {
if(request.status === 200) {
if(request.responseType === "json") {
aja.value = request.response;
} else {
aja.value = JSON.parse(request.response);
}
var parent = aja.parentElement;
var templateElements = aja.children;
for(var j=templateElements.length-1; j>=0; --j) {
var template = templateElements[j];
AJAMU.replace(
{
template: template,
value: aja.value
}
);
parent.insertBefore(template, aja.nextSibling);
}
parent.removeChild(aja);
}
}
};
request.open("GET", src);
if(request.responseType) {
request.responseType = "json";
}
request.send();
};
AJAMU.replace = function(spec) {
var templateHtml = spec.template.innerHTML;
var replace = function(spec) {
for(var property in spec.value) {
var value = spec.value[property];
if(!spec.property) {
var qualified = property;
} else {
if(Array.isArray(spec.value)) {
qualified = spec.property + "[" + property + "]";
} else {
qualified = spec.property + "." + property;
}
}
if(typeof(value) !== "string"
&& typeof(value) !== "number"
&& typeof(value) !== "boolean") {
replace({value: value, property: qualified});
} else {
var pattern = new RegExp(("{"+ qualified + "}").escapeRegExp());
templateHtml = templateHtml.replace(pattern, value);
}
}
};
replace(spec);
spec.template.innerHTML = templateHtml;
};
(function(){
window.addEventListener("load", function() {
AJAMU.initialize();
});
}());