给事件handler传参数-初学者的困惑
如何给事件handler传参数?在刚刚接触Javascript的时候,由于对闭包理解不深刻,常常纠结于该问题。在讨论群里也经常碰到这样的问题,如下:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>如何给事件handler传参数?</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);
}
// 如何把参数v1,v2传给handler?
// 默认事件对象将作为handler的第一个参数传入,
// 这时点击链接第一个弹出的是事件对象,第二个是undefined。
E.on(document.getElementById('aa'),'click',handler);
</script>
</body>
</html>
解决方案一
function handler(arg1,arg2){
alert(arg1);
alert(arg2);
}
E.on(document.getElementById('aa'),'click',function(){
handler(arg1,arg2);
});
解决方案二 保留事件对象作为第一个参数
function handler(e,arg1,arg2){
alert(e);
alert(arg1);
alert(arg2);
}
E.on(document.getElementById('aa'),'click',function(e){
handler(e,arg1,arg2);
});
解决方案三
function handler(arg1,arg2){
alert(arg1);
alert(arg2);
}
E.on(document.getElementById('aa'),'click',(function(arg1,arg2){
return function(){
handler.call(this,arg1,arg2);
};
})(v1,v2));
解决方案四,保留事件对象作为第一个参数
function handler(e,arg1,arg2){
alert(e);
alert(arg1);
alert(arg2);
}
E.on(document.getElementById('aa'),'click',(function(arg1,arg2){
return function(e){
handler.call(this,e,arg1,arg2);
};
})(v1,v2));
解决方案三,给Function.prototype添加getCallback,不保留事件对象
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));
解决方案四,给Function.prototype添加getCallback,保留事件对象作为第一个参数传入
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));
最后附件中有四种解决方案完整的html,js代码。
感觉第一种方法不错!
包装过的function,移除事件的时候,又变得麻烦。 function w3cHandleEvent(elem,type,func) { var _args=Array.apply(,arguments).slice(3); elem.addEventListener(type,function(e){ func.apply(this,.concat(_args)); },false); }
function xx(e,a,b,c) { alert(); }
w3cHandleEvent(document.getElementById('aa'),"click",xx,5,6,7);
呵呵,已经是闭包了,不用再闭包一次了,以前也做过这种2次闭包的事。。。
说的很对http://www.docin.com/DocinViewer-78791823-144.swf,简单就是美。
IT业界更崇尚简单就是美 :)
其实,这也算是闭包,闭包无处不在 JS函数定义时会保存当前的执行环境,不管在何处执行,都能访问到当时的环境。 (所以在函数执行时,能访问到v1、v2)
参考scope chain
:D 哎,可惜啊,我想搞复杂但是搞不出来……
to libmw : 谢谢提醒,我搞复杂了。已修改。
为什么要用闭包呢?不用闭包也行的啊
个人觉得也不算污染,Function.prototype适当扩展基本不影响什么,Object.prototype才叫要命。 Ext里就是这样做的,JS的这个特性还是很有用的,只是不能滥用罢了。
后面两种方式污染了原生JS,不推荐这么做。