Summary of four ways to pass parameters to an event response function

  • 2020-03-30 00:44:19
  • OfStack

How do I pass parameters to an event handler? When I first started working with Javascript, I often struggled with closures because I didn't understand them very well.

This question is also frequently encountered in discussion groups, as follows


<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title> How to give events handler The parameters? </title>
</head>
<body>
 <a href="#" id="aa">Click me</a>
 <script type="text/javascript">
  var E = {
   on : function(el, type, fn){
    el.addEventListener ?
     el.addEventListener(type, fn, false) :
     el.attachEvent("on" + type, fn);
   },
   un : function(el,type,fn){
    el.removeEventListener ?
     el.removeEventListener(type, fn, false) :
     el.detachEvent("on" + type, fn);  
   }
  };

  var v1 = 'jack', v2 = 'lily';      
  function handler(arg1,arg2){
   alert(arg1);
   alert(arg2);
  }

  //How do I pass the parameters v1, v2 to the handler?
  //The default event object is passed in as the first parameter to the handler,
  //Click on the link and the first thing that pops up is the event object, and the second is undefined.        
  E.on(document.getElementById('aa'),'click',handler);
 </script>
</body>
</html>

How do I pass the parameters v1, v2 to the handler? The default event object is passed in as the first parameter to the handler, so click on the link and the first thing pops up is the event object, and the second is undefined.

In scenario 1, no reserved event object is passed in as the first parameter


function handler(arg1,arg2){
 alert(arg1);
 alert(arg2);
}
E.on(document.getElementById('aa'),'click',function(){ 
 handler(arg1,arg2); 
});

In scenario 2, the event object is retained as the first parameter & PI;

function handler(e,arg1,arg2){
 alert(e);
 alert(arg1);
 alert(arg2);
}
E.on(document.getElementById('aa'),'click',function(e){
 handler(e,arg1,arg2);
});

In scenario 3, add getCallback to function.prototype without retaining the event object

Function.prototype.getCallback = function(){
 var _this = this, args = arguments;  
 return function(e) {
        return _this.apply(this || window, args);
    };
}
E.on(document.getElementById('aa'),'click',handler.getCallback(v1,v2));

In scenario 4, add a getCallback to function.prototype, leaving the event object as the first parameter passed in

Function.prototype.getCallback = function(){
 var _this = this, args = [];
 for(var i=0,l=arguments.length;i<l;i++){
  args[i+1] = arguments[i];
 }
 return function(e) {
  args[0] = e;
        return _this.apply(this || window, args);
    };
}
E.on(document.getElementById('aa'),'click',handler.getCallback(v1,v2));


Related articles: