Dynamically register the multi-event handler

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.onclick='alert(1)';
//elementB.onclick='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.onclick='alert(1);spyOnUser()';
//elementB.onclick='alert(2);spyOnUser()';
instead, It will reqister it as
//elementA.onclick='old();spyOnUser()';
//elementB.onclick='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 onload="trackFormChange()">
<form id="bodyForm" name="bodyForm">
  <input type=checkbox name="testcb1" onclick="alert('Element A')">Element A<BR>
  <input type=checkbox name="testcb2" onclick="alert('Element B')">Element B<BR>
  <input type=checkbox name="testcb3" onclick="alert('Element C')">Element C<BR>
</form>

</body>

</html>

==============================================================

阅读更多
上一篇JVM Notes - 1
下一篇IE is gel
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭