Repository navigation
Expand file tree
/
Copy pathtemplate.js
More file actions
64 lines (49 loc) · 1.76 KB
/
Copy pathtemplate.js
File metadata and controls
64 lines (49 loc) · 1.76 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
function Template(elem) {
function checkParent(parent) {
if (!(parent instanceof HTMLElement) || (typeof parent) === "string") {
parent = document.getElementById(parent.replace(/^#/g, ''));
}
return parent;
}
if (!elem) {
throw new Error('No ID or element specified.');
}
if (!(elem instanceof HTMLElement) || (typeof elem) === "string") {
elem = document.getElementById(elem.replace(/^#/g, ''));
}
Object.freeze(elem);
if (!('content' in elem)) {
throw new Error('Template unsupported by the browser.');
}
let fieldElems = elem.content.querySelectorAll('[data-field]');
let fields = {};
let fieldVals = {};
fieldElems.forEach(function (fieldElem) {
//console.log(f);
if (!fields[fieldElem.dataset.field]) {
fields[fieldElem.dataset.field] = [];
}
fieldVals[fieldElem.dataset.field] = fieldElem.innerHTML;
fields[fieldElem.dataset.field].push(fieldElem);
});
this.fields = new Proxy(fieldVals, {
set: function (obj, prop, val) {
//console.log(obj, prop, val);
if (prop in fields) {
fields[prop].forEach(function (f) {
f.innerHTML = val;
});
obj[prop] = val;
}
},
get: function (obj, prop) {
return obj[prop] || null;
}
});
this.appendTo = function (parent = document.body) {
checkParent(parent).appendChild(elem.content.cloneNode(true));
}
this.prependTo = function (parent = document.body) {
checkParent(parent).prepend(elem.content.cloneNode(true));
}
}