关于 addEventListener 和 handleEvent 方法

 

使用 addEventListener 可以绑定事件,并传入回调函数。

Mozilla 0.9.1 和 Netscape 6.1 之后的版本不但支持传递函数引用,也都允许直接把拥有 handleEvent 方法的对象作为 addEventListener 方法的第二参数。

这在 DOM Level 2 的接口定义中也已经做了说明:

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);
        }
        // 黑莓等系统不支持 handleEvent 方法
        catch(e) {
            if(typeof fn == 'object' && fn.handleEvent) {
                el.addEventListener(ev, function(e){
                    //以第一参数为事件对象
                    fn.handleEvent.call(fn, e);
                }, bubble);
            } else {
                throw e;
            }
        }
    } else if(el.attachEvent) {
        // 检测参数是否拥有 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

原文地址:https://www.cnblogs.com/macliu/p/5661230.html