-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom-builder.js
105 lines (87 loc) · 2.94 KB
/
dom-builder.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
96
97
98
99
100
101
102
103
104
105
/**
@param {HTMLElement} parent
@param {Array} tagNames
*/
function domBuilder(parent, tagNames) {
var $get = YAHOO.util.Dom.get;
var parent_el = $get(parent);
//private state variables
var context_stack = [];
var that = {
rootNode: parent_el,
currentNode: parent_el,
document: parent_el.document,
/*
* add
* @param {String} tag
* @param {Object|Function} attributes
*/
add: function(tag, attributes) {
if (YAHOO.lang.isFunction(attributes)) {
attributes = attributes();
}
var el = document.createElement(tag);
for (name in attributes) {
el.setAttribute(name, attributes[name]);
}
this.currentNode.appendChild(el);
this.currentNode = el;
return this;
},
/*
* text
* @param {String|Function} s
*/
text: function(s) {
if (YAHOO.lang.isFunction(s)) {
s = s();
}
if (!YAHOO.lang.isString(s)) throw 'argument to text() must be a string or a function that returns a string!';
this.currentNode.innerHTML = s;
return this;
},
/*
* end
*/
end: function() {
/*
* Close first parent
*/
if (this.currentNode !== this.rootNode) {
this.currentNode = this.currentNode.parentNode;
}
return this;
},
on: function(evt, fn) {
YAHOO.util.Event.addListener(this.currentNode, evt, fn);
return this;
},
each: function(collection) {
context_stack.push({
node: this.currentNode,
collection: collection
});
return this;
}
}; //that
autotags = ['div', 'span', 'table', 'tr', 'td', 'a', 'img', 'p', 'pre', 'code',
'ul', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'input'];
if (tagNames && tagNames.length > 0) {
autotags = autotags.concat(tagNames);
}
for (i in autotags) {
// add the tags as functions on 'that'. But don't overwrite any existing properties!
// these are just helpers that wrap calls to 'add'
tag = autotags[i];
if (!that[tag]) {
(function() {
//need extra function and var to capture the current value of tag, b/c of closures.
var t = tag;
that[t] = function(attributes) {
return that.add(t, attributes);
}
})();
}
}
return that;
}