博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

handleEvent addEventListener

Posted on 2013-07-08 14:31  bw_0927  阅读(164)  评论(0)    收藏  举报

http://www.cnblogs.com/dindog/archive/2012/01/13/2322100.html

http://peter.michaux.ca/articles/our-backwards-dom-event-libraries

http://www.thecssninja.com/javascript/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(); 就把监听调用的方法改了,很棒,是不是?