elWraper.onclick = (function(){
// misc stuff here
//event handler
return function(e){
e = e || window.event;
var t = e.target || e.srcElement;
//manipulations with "t" variable
}
})();
In standards compliant browsers the event object is the first parameter passed into the callback function. In IE it is a global variable (which is what e = e || window.event
is trying to determine). Therefore, the function that you return by the immediately executed function
should accept the event object declared as its first (and usually only) argument.
Clarification
Since people are wondering (and probably they are wondering why the OP accepted this instead answer) there are uses for this that is not clear from the OP's question. One is to create a closure to a variable to track something:
/* Count number of clicks,
* WITHOUT USING GLOBAL VARS!
*/
el.onclick = (function(){
var counter = 0;
return function(e){
e = e || window.event;
var t = e.target || e.srcElement;
counter ++;
alert('detected '+counter+' clicks!');
// do stuff with t or e ...
}
})();
also, this is the classic way of assigning event handlers in loops:
/* Use double closure to break closure in loop!
*/
for (var i=0; i<stuff.length; i++) {
var el = stuff[i];
el.onclick = (function(x){
return function(e){
e = e || window.event;
var t = e.target || e.srcElement;
alert(x);
// do stuff with t or e ...
}
})(i);
}
Or maybe the OP just thought that he could 'cache' the event object and mistakenly believed he could use this to do it. In which case, reading my explanation (instead of just the code) should enlighten the reader as to why that would be a bad idea.