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
