chuanxshi / javascript-patterns

JavaScript Design Patterns

Home Page:http://shichuan.github.io/javascript-patterns

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

addEventListener and attachEvent check

tj opened this issue · comments

is somewhat "wrong", I wouldn't nitpick but this is supposed to be about best practices :p

Anyway, it mentions that the typeof check is better, which it's really not, you're doing little more than the example
above it, if anything you should do 'function' == typeof in that case, but even then I wouldn't call that best practice
unless you're paranoid

It should definitely be testing for callability (by "function" == typeof). +1.

i have updated the image because that example is never in the collection. I updated this issue title and added the original patterns plus the one you suggested below:

if (navigator.userAgent.indexOf("MSIE")!==-1){
    document.attachEvent('onclick',doSomething);
}

if (document.attachEvent) {
    document.attachEvent('onclick',doSomething);
}

if (typeof document.attachEvent!=="undifined") {
    document.attachEvent('onclick',doSomething);
}

if (typeof document.attachEvent!=="undifined") {
    document.attachEvent('onclick',doSomething);
}

if (typeof window.addEventListener === "function") {
  // ...
} else {
    document.attachEvent('onclick',doSomething);
}