0

I am trying to invoke addEventListener through apply with the code below but I am getting "TypeError: Type error" in webkit's console.

addEvent = (function (handler) {
  return function (element, event, fn) {
    handler.apply(element, [event, fn, false]);
  };
}(addEventListener || attachEvent));

I have tried both apply and call to invoke the method but to no avail. Am I missing something obvious or trying to do something not allowed for some reason I don't know yet?

Another article is talking about this a little bit but not exactly how I am trying to work with it; Using native code functions as JavaScript objects in WebKit.

Community
  • 1
  • 1
kalisjoshua
  • 2,306
  • 2
  • 26
  • 37
  • 2
    You are breaking a few abstractions here. `window.addEventListener.apply(anElement, [...])` is not guaranteed to be the same as `anElement.addEventListener()`, namely because the DOM api's are implemented via host (os) objects that are not required to align with the language spec (i.e. they're different specs). Further, IE's *attachEvent* requires an `"on"` prefix for the event name passed. – Crescent Fresh Aug 06 '11 at 02:46
  • This is my first time posting to Stack and I love it. So glad there are people out there smarter than me and willing to help. Would a better way to do this be something like this: element[handler.name](event, fn, false); – kalisjoshua Aug 06 '11 at 13:25

1 Answers1

1

Another way of accomplishing this (properly - as noted by Crescent Flash) is as follows :

addEvent = (function () {   
  return addEventListener ? 
    function (element, event, fn) {
      element.addEventListener (event, fn, false); 
    } :
    function (element, event, fn) { 
      element.attachEvent ('on' + event, fn); 
    };
}) ();

This could then be extended to reduce the other differences between the two event models.

HBP
  • 15,685
  • 6
  • 28
  • 34
  • Not a bad idea but I think it would be better to do the if check outside of the returned function so that it is evaluated only once. Taking advantage of the closure I created an "on" variable and set it before returning the function and just use it in the function. var on = handler.name === "attachEvent" ? "on" : ""; and then inside the returned function: element[handler.name](on + event, fn, false); I just wonder if this works in IE since I am at home and only on a mac. – kalisjoshua Aug 06 '11 at 13:37
  • kalisjoshua : You are quite right. I completed the closure code, now addEvent has the value of one or the other interior functions. – HBP Aug 06 '11 at 16:17