addEventListener 传入带 handleEvent 的对象

element.addEventListener(event, callback [,capture] );

上面是一个典型JavaScript绑定事件方法,很简单。可是今天发现,原来第二个参数除了可以传入函数外,还可以传入对象。也就是可以写成:

element.addEventListener(event, object [,capture] );

 

事件会自动在传入对象中寻找handleEvent方法,也就是 object.handleEvent。这样有什么好处呢?看例子:

复制代码
obj = {
init: function(){
element.addEventListener('event', this, 0);
},
 
handleEvent: function(event){
this.method();
},

method: function (){
alert(this.Name);
/*
//////////////
*/
},

Name: 'obj has an name!',
}

obj.init();
复制代码

 

这样,在 element 触发event事件后,调用的是handleEvent 方法,注意这里面的 this 是指向对象本身 (即 this ==obj //true),这个我们调用对象里面的方法提供极大的便利!而普通的函数,this传入函数里面的this 是指向事件的,因事件类型不同而不同。

 

除了上面这点外,还可以直接修改对象,而不用删除、重新监听事件:

复制代码
obj._handleEvent = function(){
/*
另外的方法
*/
}

obj.changeHandler = function(){
this.tmp = this.handleEvent;
this.handleEvent = this._handleEvent;
this._handerEvent = this.tmp;
this.tmp = null;
}
复制代码

只要obj.changeHandler(); 就把监听调用的方法改了,很棒,是不是?

posted @ 2012-10-15 14:31  CatherineGao  阅读(409)  评论(0编辑  收藏  举报