ITeye博客

给事件handler传参数-初学者的困惑

zhouyrt · 2010-09-27 10:18 · Core JS · Web前端 · Markdown

如何给事件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代码。

评论(12)

  1. #12 楼 · fch415 · 2010-10-15 21:08
    
    var E = {
        _fns:{}, 
        _wrapped: function(type, fn, context){//一个便于传递更多函数上下文参数的包装函数
             var me = this;
             var wfn = function(e){
                 fn.apply(me || window, [e, context]);
             }
             this._fns[type] = [fn, wfn];//把fn和wfn都缓存起来,在Unload时强制释放以免IE内存泄露
             return wfn;
        },  
        on : function(el, type, fn, context){				
            el.addEventListener ?   
                el.addEventListener(type, this._wrapped(type, fn, context), false) :   
                el.attachEvent("on" + type, this._wrapped(type, fn, context));   
        }
    };   
    
    var v1 = 'jack', v2 = 'lily';   
            
    //如此传递上下文参数岂不更加自然,又避免给Function加一个用途很窄且不必要的原型函数           
    E.on(document.getElementById('aa'), 'click', function(e, arg){   
        alert(e)
        alert(arg);  
    }, [v1,v2]); 
    
    
  2. #11 楼 · ol_beta · 2010-10-07 16:00

    感觉第一种方法不错!

  3. #10 楼 · xukang · 2010-10-04 19:58

    包装过的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);

  4. #9 楼 · lixinlixin2008 · 2010-10-02 18:02

    clue writes:

    [quote=libmw][code=java] function handler(e,arg1,arg2){ alert(e); alert(arg1); alert(arg2); } E.on(document.getElementById('aa'),'click',function(e){ handler(e,v1,v2); }); [/code] 为什么要用闭包呢?不用闭包也行的啊[/quote] 其实,这也算是闭包,闭包无处不在 JS函数定义时会保存当前的执行环境,不管在何处执行,都能访问到当时的环境。 (所以在函数执行时,能访问到v1、v2)

    参考scope chain

    呵呵,已经是闭包了,不用再闭包一次了,以前也做过这种2次闭包的事。。。

  5. #8 楼 · 飞语001 · 2010-10-01 09:33

    KimHo writes:

    [quote=libmw][quote=zhouyrt]to libmw : 谢谢提醒,我搞复杂了。[/quote] :D 哎,可惜啊,我想搞复杂但是搞不出来……[/quote] IT业界更崇尚简单就是美 :)

    说的很对http://www.docin.com/DocinViewer-78791823-144.swf,简单就是美。

  6. #7 楼 · KimHo · 2010-09-30 17:14

    libmw writes:

    [quote=zhouyrt]to libmw : 谢谢提醒,我搞复杂了。[/quote] :D 哎,可惜啊,我想搞复杂但是搞不出来……

    IT业界更崇尚简单就是美 :)

  7. #6 楼 · clue · 2010-09-30 11:53

    libmw writes:

    [code=java] function handler(e,arg1,arg2){ alert(e); alert(arg1); alert(arg2); } E.on(document.getElementById('aa'),'click',function(e){ handler(e,v1,v2); }); [/code] 为什么要用闭包呢?不用闭包也行的啊

    其实,这也算是闭包,闭包无处不在 JS函数定义时会保存当前的执行环境,不管在何处执行,都能访问到当时的环境。 (所以在函数执行时,能访问到v1、v2)

    参考scope chain

  8. #5 楼 · libmw · 2010-09-30 11:22

    zhouyrt writes:

    to libmw : 谢谢提醒,我搞复杂了。

    :D 哎,可惜啊,我想搞复杂但是搞不出来……

  9. #4 楼 · zhouyrt · 2010-09-30 08:00

    to libmw : 谢谢提醒,我搞复杂了。已修改。

  10. #3 楼 · libmw · 2010-09-29 17:02
    
    function handler(e,arg1,arg2){
       alert(e);
       alert(arg1);
       alert(arg2);
    }
    E.on(document.getElementById('aa'),'click',function(e){	
       handler(e,v1,v2);	
    });
    
    

    为什么要用闭包呢?不用闭包也行的啊

  11. #2 楼 · clue · 2010-09-28 09:00

    pfans writes:

    后面两种方式污染了原生JS,不推荐这么做。

    个人觉得也不算污染,Function.prototype适当扩展基本不影响什么,Object.prototype才叫要命。 Ext里就是这样做的,JS的这个特性还是很有用的,只是不能滥用罢了。

  12. #1 楼 · pfans · 2010-09-28 07:52

    后面两种方式污染了原生JS,不推荐这么做。

评论功能维护中,当前仅展示历史评论。