addEventListener 的另类写法

addEventListener 参数以下javascript

addEventListener(type, listener[, useCapture]);
  1. type,事件名称
  2. listener,事件处理器
  3. useCapture,是否捕获

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

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

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

 

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

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

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

 

简化为以下测试代码github

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)ui

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

 

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

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

相关文章
相关标签/搜索