Created
August 29, 2012 04:37
-
-
Save wiky/3506887 to your computer and use it in GitHub Desktop.
Serial Event Listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function addEvent(el, type, handler) { | |
if (el.attachEvent) { // IE | |
// 为元素的事件类型创建一个哈希表 | |
el._events = el._events || {}; | |
if (!handler) { | |
return; | |
} | |
// 取得事件处理函数的数组的引用 | |
var handlers = el._events[type]; | |
if (handlers) { | |
if (typeof handler._index === 'undefined' || handlers[handler._index] !== handler) { | |
// 将事件处理函数存入数组 | |
handlers.push(handler); | |
// 为事件处理函数增加索引 | |
handler._index = handlers.length - 1; | |
} | |
} else { | |
// 创建事件处理函数的数组 | |
el._events[type] = []; | |
// 缓存总的事件绑定函数 | |
el._eventHandlers = function(e) { | |
e = e || window.event; | |
var handlers = el._events[type]; | |
// 依次执行所有缓存的事件处理方法 | |
for (var i = 0, len = handlers.length; i < len; i++) { | |
typeof handlers[i] === 'function' && handlers[i](e); | |
} | |
}; | |
// 绑定一次事件,来处理所有绑定在该事件上的所有函数 | |
el.attachEvent('on' + type, el._eventHandlers); | |
addEvent(el, type, handler); | |
} | |
} else { // 现代浏览器 | |
el.addEventListener(type, handler, false); | |
} | |
} | |
function removeEvent(el, type, handler) { | |
if (el.detachEvent) { // IE | |
// 取得事件处理函数的数组的引用 | |
var handlers = el._events && el._events[type]; | |
if (handlers) { | |
if (handler) { | |
// 删除事件处理函数队列里的函数 | |
delete handlers[handler._index]; | |
// 删除函数的索引 | |
delete handler._index; | |
if (handlers.length === 0) { | |
// 解除总的事件绑定 | |
el.detachEvent('on' + type, el._eventHandlers); | |
} | |
} else { | |
// 解除总的事件绑定 | |
el.detachEvent('on' + type, el._eventHandlers); | |
// 删除该事件绑定上的所有事件处理函数队列 | |
delete el._events[type]; | |
} | |
} | |
} else { // 现代浏览器 | |
el.removeEventListener(el, type, handler); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment