This example demonstrates
Event Delegation in JavaScript; or, at least, my interpretation of this topic
Event delegation has two related meanings. In languages other than JS a
delegate is an object that is created specifically to respond to an event on an object (or objects). The simpler meaning for this example is the following:
Quote:
|
We attach an event to a parent object and, when the event occurs, we discover which specific child-element was the target of the event.
|
People commonly loop through rows of a table, or list-items, attaching an event (such as click) to each row/td or item. Depending on how the event is attached, each element may obtain their own copy of the event. This is inefficient and can largely be avoided.
The following example attaches the click event to the (parent) ol-element. When this is clicked we respond to the event BUT ONLY FOR LI-ITEMS. The counter confirms that there is only one instance of the alertText() function.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
<script type="text/javascript">
var addEvent = function (elem, eventType, func) {
if ( elem.addEventListener )
addEvent = function (elem, eventType, func) {
elem.addEventListener(eventType, func, false);
};
else if ( elem.attachEvent )
addEvent = function (elem, eventType, func) {
elem.attachEvent('on' + eventType, func);
};
else
addEvent = function (elem, eventType, func) {
elem['on' + eventType] = func;
};
addEvent(elem, eventType, func);
};
var delegateEvent = function (elem, childElems, eventType, func) {
addEvent(elem, eventType, function (e) {
var evt = e || window.event;
var elem = evt.target || evt.srcElement;
if ( elem.nodeName.toLowerCase() === childElems.toLowerCase() ) {
func(elem);
}
});
}
function alertText(obj) {
this.counter = this.counter || 1;
alert(counter++ + ' hits :' + obj.innerHTML);
}
function init() {
delegateEvent(document.getElementById('thelist'), 'li', 'click', alertText);
}
addEvent(window, 'load', init);
</script>
</head>
<body>
<ul id="thelist">
<li>The first line</li>
<li>.. and the second one</li>
<li>just a third..</li>
<li>and finally, a fourth.</li>
</ul>
</body>
</html>