This example shows different approaches to attaching and detaching events: manual events observing, using Prototype, and solution by Dean Edwards.
Take into account that there are 5000 elements in the list, and in real-world applications you should not use such amount (or you have to redesign your application).
There are three buttons you could see below: “manually” would start manual events attaching function, “prototype.js” — attaching events using Prototype JavaScript framework, “addEvent” — Dean Edwards solution. When you click on any button, corresponding test code will be shown below it.
manually prototype.js addEvent
Attaching time: --. Detaching time: --
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| // Attaching events
for (var i = items.length; i--; ) {
if (items[i].addEventListener) {
items[i].addEventListener('click', e_onclick, false);
} else if (items[i].attachEvent) {
items[i].attachEvent('onclick', e_onclick);
}
}
// Detaching events
for (var i = items.length; i--; ) {
if (items[i].removeEventListener) {
items[i].removeEventListener('click', e_onclick, false);
} else if (items[i].detachEvent) {
items[i].detachEvent('onclick', e_onclick);
}
} |
1 2 3 4 5 6 7 8
| // Attaching events
for (var i = items.length; i--; ) {
Event.observe(items[i], 'click', e_onclick, false);
}
// Detaching events
for (var i = items.length; i--; ) {
Event.stopObserving(items[i], 'click', e_onclick, false);
} |
1 2 3 4 5 6 7 8
| // Attaching events
for (var i = items.length; i--; ) {
addEvent(items[i], 'click', e_onclick);
}
// Detaching events
for (var i = items.length; i--; ) {
removeEvent(items[i], 'click', e_onclick);
} |