Dynamically register the multi-event handler
Found something interesting in this page.
http://www.quirksmode.org/js/events_tradmod.html
It provides us the way to dynamically register more than one event handler like this:
var old = (element.onclick) ? element.onclick : function () {};
element.onclick = function () {old(); spyOnUser()};
The code snippet will get the previous handler if any and register it to the event together with the spyOnUser. However, if you want to apply this to multi-elements, you will find that it doesn't work for you. Considering the following code snippet:
//elements is the array which contains elementA and elementB and they have the following pre-defined event handler:
//elementA.οnclick='alert(1)';
//elementB.οnclick='alert(2)';
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var old = (element.onclick) ? element.onclick : function () {};
element.onclick = function () {old(); spyOnUser()};
}
It is totally wrong if you thought that the above code snippet will change the registered event hander as:
//elementA.οnclick='alert(1);spyOnUser()';
//elementB.οnclick='alert(2);spyOnUser()';
instead, It will reqister it as
//elementA.οnclick='old();spyOnUser()';
//elementB.οnclick='old();spyOnUser()';
and the internal logic of old() is the "alert(2)"(the first invocation will create old() function with alert(1) and the second one will update it to alert(2))
In order to make it work in such scenario, You should write the code as
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
eval('var old' + i + '=' + 'element.onclick;'
+ ' element.onclick = function () {old' + i + '(); spyOnUser()}');
}
I really learn a lot from this practice; please rectify me, If there is anything wrong in my code snippet and my understanding.
You may want to try this html to get more about this.
===============================Source Code=================================
<html>
<head>
<script language="Javascript">
function spyOnUser() {
alert('spyOnUser Method');
}
function trackFormChange() {
for (var i = 0; i<document.bodyForm.elements.length; i++) {
var element = document.bodyForm.elements[i];
if (element.type == "checkbox") {
eval('var old' + i + '=' + 'element.onclick;'
+ ' element.onclick = function () {old' + i + '(); spyOnUser()}');
}
}
}
</script>
</head>
<body οnlοad="trackFormChange()">
<form id="bodyForm" name="bodyForm">
<input type=checkbox name="testcb1" οnclick="alert('Element A')">Element A<BR>
<input type=checkbox name="testcb2" οnclick="alert('Element B')">Element B<BR>
<input type=checkbox name="testcb3" οnclick="alert('Element C')">Element C<BR>
</form>
</body>
</html>
==============================================================