您的位置:首页 > 其它

addEventListener 的另类写法

2015-10-15 07:59 579 查看
addEventListener 参数如下

addEventListener(type, listener[, useCapture]);


type,事件名称

listener,事件处理器

useCapture,是否捕获

一直把 listener 记成是响应函数,function 类型。相信很多人也是这么理解的。多数时候是这么使用

elem.addEventListener('click', function(ev) {
// todo
}, false);


第一个参数没什么异议,第二个参数传一个 function,第三个参数传 false,事件流为了和低版本IE保持一致(都冒泡)。

在读 iscroll.js(5.1.3) 源码时发现还有这样一种写法

// _initEvents 863行,方法
eventType(window, 'orientationchange', this);
eventType(window, 'resize', this);

// eventType 42行,如下
me.addEvent = function (el, type, fn, capture) {
el.addEventListener(type, fn, !!capture);
};


简化为如下测试代码

var obj = {handleEvent: function(ev) {
console.log(ev)
}}
document.addEventListener('click', obj, false)


  

没错,第二个参数不是 function,而是一个 object。一下糊涂了,世界观一时半会没改变过来。怎么能是一个对象呢?惯性思维和不看规范带来的后患是巨大的。点击文档没有报错,说明确实是可以这么使用的。

实际 W3C DOM2 Events 里定义的 listener,没说必须是 function 类型。

Interface EventListener (introduced in DOM Level 2)



只要实现了以上接口就都能作为 listener,简单说只要给对象添加 handleEvent 方法就可以作为 listener了。

通过这种方式添加事件的一好处就是当你采用类式开发时 this 能轻松的绑定到当前类上。如下

function Component(elem, option) {
this.elem = elem
this.handleEvent = function(ev) {
if (ev.type === 'click') {
this.updateNav()
}
if (ev.type === 'dblclick') {
this.updateBottom()
}
}
this.init()
}
Component.prototype = {
init: function() {
this.elem.addEventlistener('click', this, false)
this.elem.addEventlistener('dblclick', this, false)
},
updateNav: function() {
console.log('nav update')
},
updateBottom: function() {
console.log('bottom update')
}
}


相关:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener

https://github.com/snandy/e.js
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: