使用 addEventListener 可以綁定事件,并傳入回調(diào)函數(shù)。
Mozilla 0.9.1 和 Netscape 6.1 之后的版本不但支持傳遞函數(shù)引用,也都允許直接把擁有 handleEvent 方法的對象作為 addEventListener 方法的第二參數(shù)。
這在 DOM Level 2 的接口定義中也已經(jīng)做了說明:
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener
利用這個特性可以把任意對象注冊為事件處理程序,只要它擁有 handleEvent 方法。
var o = { handleEvent : function () { alert('handleEvent executed'); }};element.addEventListener('click', o, false);
當定義對象封裝的時候,可以直接將 this 指針傳入:
var o = { bind : function () { element.addEventListener('click', this, false); }, handleEvent : function () { alert('handleEvent executed'); }};
IE9 是 IE 家族中第一個支持 addEventListener + handleEvent 的瀏覽器,IE9 之前的版本連 addEventListener 也沒能支持。需要通過屬性探測解決兼容問題:
function on(el, ev, fn, bubble) { if(el.addEventListener) { try { el.addEventListener(ev, fn, bubble); } // 黑莓等系統(tǒng)不支持 handleEvent 方法 catch(e) { if(typeof fn == 'object' && fn.handleEvent) { el.addEventListener(ev, function(e){ //以第一參數(shù)為事件對象 fn.handleEvent.call(fn, e); }, bubble); } else { throw e; } } } else if(el.attachEvent) { // 檢測參數(shù)是否擁有 handleEvent 方法 if(typeof fn == 'object' && fn.handleEvent) { el.attachEvent('on' + ev, function(){ fn.handleEvent.call(fn); }); } else { el.attachEvent('on' + ev, fn); } }}
完。
參考資料:
http://www.thecssninja.com/javascript/handleevent
http://topic.csdn.net/t/20040628/14/3128262.html
《本文來源:芒果小站,原文:http://www.mangguo.org/addeventlistener-and-handleevent/》