Using the method .attachEvent()
in IE, how can I reference the caller object (the element that triggered the event) with this
? In normal browsers, using .addEventListener
, the var this
points to the element, while in IE it points to the window
object.
I need it to work with the following code:
var element = //the element, doesn't matter how it is obtained
element.addAnEvent = function(name, funct){
if(element.addEventListener) // Works in NORMAL browsers...
else if(element.attachEvent){
element.attachEvent("on"+name, funct);
//where the value of "this" in funct should point to "element"
}
}
I just made that code up, it's not exactly the same as my code, but if it works with it then it works with me!
Bind it. Well, you can't use
Function.prototype.bind
that gets added in javascript 1.8.5, but you can use closure andFunction.prototype.apply
.From this quirksmode article with regard to
attachEvent
:I haven't tested it, but a possible workaround may be to wrap the handler in an anonymous function that calls your handler via
funct.call()
.My apologies for the untested solution. I don't like doing that, but can't easily get to IE right now.
If you're in IE, you can get the "caller" object, as you call it, by accessing
window.event.srcElement
within the event handler function. This object is normally referred to as the event target or source.This code is untested, but should set you off in the right direction.
I think it would be better to extend the
Element
object , through the prototype chain, instead of adding your method to each element you want to add events to (works with all browsers)..This way it will work for all your current and future elements (and you only have to run it once).