Correct usage of addEventListener() / attachEvent()?

▼魔方 西西 提交于 2019-11-26 06:54:49

The usage of both is similar, though both take on a slightly different syntax for the event parameter:

addEventListener (mdn reference):

obj.addEventListener('click', callback, false);

function callback(){ /* do stuff */ }

Events list for addEventListener.

attachEvent (msdn reference):

obj.attachEvent('onclick', callback);

function callback(){ /* do stuff */ }

Events list for attachEvent.

Arguments

For both of the methods the arguments are as follows:
1. Is the event type.
2. Is the function to call once the event has been triggered.
3. (addEventListener only) If true, indicates that the user wishes to initiate capture.

Explanation

Both methods are used to achieve the same goal of attaching an event to an element.
The difference being is that attachEvent can only be used on older trident rendering engines ( IE5+ IE5-8*) and addEventListener is a W3 standard that is implemented in the majority of other browsers (FF, Webkit, Opera, IE9+).

For solid cross browser event support including normalizations that you won't get with the Diaz solution use a framework.

*IE9-10 support both methods, for backwards compatibility.

Thanks to Luke Puplett for pointing out that attachEvent has been removed from IE11.

Minimal cross browser implementation

As Smitty recommended you should take a look at this Dustin Diaz addEvent for a solid cross browser implementation without the use of a framework:

function addEvent(obj, type, fn) {
  if (obj.addEventListener) {
    obj.addEventListener(type, fn, false);
  }
  else if (obj.attachEvent) {
    obj["e"+type+fn] = fn;
    obj[type+fn] = function() {obj["e"+type+fn](window.event);}
    obj.attachEvent("on"+type, obj[type+fn]);
  }
  else {
    obj["on"+type] = obj["e"+type+fn];
  }
}

addEvent( document, 'click', function (e) {
  console.log( 'document click' )
})
Smitty

Anyone still hitting this discussion and not finding the answer they were looking for checkout:
http://dustindiaz.com/rock-solid-addevent

This is one of the most elegant solutions I found for those of us with restrictions on using the frameworks.

function addEvent(obj, type, fn) {

    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
        EventCache.add(obj, type, fn);
    } else if (obj.attachEvent) {
        obj["e" + type + fn] = fn;
        obj[type + fn] = function() {
            obj["e" + type + fn](window.event);
        }
        obj.attachEvent("on" + type, obj[type + fn]);
        EventCache.add(obj, type, fn);
    } else {
        obj["on" + type] = obj["e" + type + fn];
    }

}

var EventCache = function() {

    var listEvents = [];
    return {
        listEvents: listEvents,
        add: function(node, sEventName, fHandler) {
            listEvents.push(arguments);
        },
        flush: function() {
            var i, item;

            for (i = listEvents.length - 1; i >= 0; i = i - 1) {
                item = listEvents[i];
                if (item[0].removeEventListener) {
                    item[0].removeEventListener(item[1], item[2], item[3]);
                };

                if (item[1].substring(0, 2) != "on") {
                    item[1] = "on" + item[1];
                };

                if (item[0].detachEvent) {
                    item[0].detachEvent(item[1], item[2]);
                };

                item[0][item[1]] = null;
            };
        }
    };
}();

addEvent(window, 'unload', EventCache.flush);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!