chuanxshi / javascript-patterns

JavaScript Design Patterns
http://shichuan.github.io/javascript-patterns
9.39k stars 1.69k forks source link

addEventListener and attachEvent check #51

Closed tj closed 11 years ago

tj commented 12 years ago

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

michaelficarra commented 12 years ago

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

chuanxshi commented 12 years ago

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);
}