-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistBox.js
104 lines (89 loc) · 3.57 KB
/
listBox.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
//
// Atto ListBox : convert a raw list of DOM nodes into a simple list widget
//
// author: Ryan Corradini
// date: 6 July 2012
// license: MIT
//
define(
["atto/core","atto/lmnt","atto/event","require"],
function(atto, lmnt, AttoEvent) {
// make sure the appopriate CSS has been loaded for this widget
var forWidget = "atto-listbox";
if (!document.querySelector("style[data-for-widget='"+forWidget+"']")) {
require(["text!atto/listBox.css"], function(rawCss) { atto.addWidgetCss(rawCss, forWidget); });
}
function constructor(rootNode, optArgs) {
var _root = rootNode || document.createElement('div'),
_currItem = null,
i = 0,
nd = null,
nCount = _root.childElementCount || lmnt.childElementCount(_root),
lastId = 0,
_registry = {},
options = optArgs || {},
_events = {
itemSelected: new AttoEvent('atto.listBox.itemSelected')
},
__frag = document.createDocumentFragment(),
itemCount = 0;
function _getUniqueId() {
var newVal = 'aw-list-item-' + lastId++;
_registry[newVal] = newVal;
return newVal;
}
function _addItem(id, label, appendTo) {
var sID = '',
ndItem = null;
appendTo = appendTo || _root;
sID = id || _getUniqueId();
itemCount += 1;
ndItem = document.createElement('li');
ndItem.className = 'aw-listitem';
ndItem.id = sID;
ndItem.innerHTML = label;
ndItem.onclick = function() {
return function() {
if (_currItem != this) {
_currItem.classList.remove('selected');
_currItem = this;
this.classList.add('selected');
_events.itemSelected.dispatch({
item: this.id
});
}
}
}();
appendTo.appendChild(ndItem);
if (itemCount==1) {
_currItem = ndItem;
ndItem.classList.add('selected');
}
}
// grab any child elements (not raw text nodes) to form my initial tabs
var elems = lmnt.children(_root);
for (i=0; i<nCount; i++) {
nd = elems[i];
_addItem(nd.id, nd.innerHTML, __frag);
}
// ensure we've got a malleable container node (ul, not select or p or...)
if (_root && _root.nodeName != 'UL') {
var newRoot = document.createElement('ul');
newRoot.id = _root.id;
newRoot.className = _root.className;
_root.parentElement.replaceChild(newRoot, _root);
_root = newRoot;
}
_root.innerHTML = '';
_root.classList.add('aw-listbox');
_root.appendChild(__frag);
return {
root : _root,
addItem : _addItem,
events : _events,
currentItem : function() { return _currItem; }
} // end of public interface
} // end of constructor
return constructor;
} // end function
);