-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
95 lines (78 loc) · 1.74 KB
/
index.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
/**
* Module dependencies
*/
var isArray = require('isArray'),
isObject = require('isObject');
/**
* Export `json-to-dom`
*/
module.exports = json_to_dom;
/**
* Dataset mappings
*/
var map = {
'text' : 'innerText',
'html' : 'innerHTML'
};
/**
* json-to-dom
*
* @param {DomNode} el
* @param {Mixed} val
* @return {DomNode}
*/
function json_to_dom(el, val, key, obj) {
obj = obj || {};
var node = el;
if(key && typeof key == 'string')
node = el.querySelector('.' + key);
if(!node) return el;
if(isArray(val)) {
var out = [], clone;
for(var i = 0, len = val.length; i < len; i++) {
clone = node.cloneNode(true);
clone = json_to_dom(clone, val[i], i);
out.push(clone.innerHTML);
}
node.innerHTML = out.join('');
} else if(isObject(val)) {
for(var k in val) {
if(val.hasOwnProperty(k)) {
json_to_dom(node, val[k], k, val);
}
}
} else {
var keyNode = node.querySelector('.key'),
dataset = node.dataset,
values = [];
Object.keys(dataset).forEach(function(attr) {
var dsv = dataset[attr],
val = obj[dsv] || val;
delete dataset[attr];
attr = map[attr] || attr;
if(keyNode) set(keyNode, attr, val);
else if(typeof key != 'number') set(node, attr, val);
values.push(dsv);
});
if(!values.length || !~values.indexOf(key)) {
if(keyNode) set(keyNode, 'innerText', val);
else if(typeof key != 'number') set(node, 'innerText', val);
}
}
return el;
}
/**
* Set
*/
function set(node, attr, val) {
val = val || '';
switch(attr) {
case 'innerHTML':
case 'innerText':
node[attr] = val;
break;
default:
node.setAttribute(attr, val);
}
return node;
}