PDA

View Full Version : Shim for window.attachEvent implemented with Ext Core



neenhouse
8 Mar 2012, 12:21 PM
Hey everybody,

I have been wrestling a little bit with a relatively simple task. I am updating a legacy system to implement cross-browser API using ext-core and some hand-rolled stuff, but in some cases I need to use a shim. In particular, I need to shim "window.attachEvent" to support compatibility to attach a load and unload event to the window.

So far this is what I have:



if(!window.attachEvent){
window.attachEvent = function(ev,fn){
ev = ev.replace(/^on(.*)/g, "$1"); // slice "on" convention that IE implements, let adapter do the work
Ext.fly(window).on(ev, fn);

}
}


However, in Firefox, it seems sometimes the shim works and other times it throws a browser error:



// private
doAdd = function() {
var ret;
if (win.addEventListener) {
ret = function(el, eventName, fn, capture) {
if (eventName == 'mouseenter') {
fn = fn.createInterceptor(checkRelatedTarget);
el.addEventListener(MOUSEOVER, fn, (capture));
} else if (eventName == 'mouseleave') {
fn = fn.createInterceptor(checkRelatedTarget);
el.addEventListener(MOUSEOUT, fn, (capture));
} else {
el.addEventListener(eventName, fn, (capture)); // el.addEventListener is not a function
}
return fn;
};
} else if (win.attachEvent) {
ret = function(el, eventName, fn, capture) {
el.attachEvent("on" + eventName, fn);
return fn;
};
} else {
ret = function(){};
}
return ret;
}(),


I think the general problem has to do with the different browser nuisances with implement the window object. I just want a simple and elegant way to design my shim that will work. I suppose I could also just do this:



if(!window.attachEvent){
window.attachEvent = function(ev,fn){
ev = ev.replace(/^on(.*)/g, "$1"); // slice "on" convention that IE implements, let
adapter do the work
switch(ev){
case "load":
if(window.addEventListener){
window.addEventListener("load",fn,false);
} else {
window.addEventListener("onload",fn);
}
break;
case "unload":
if(window.addEventListener){
window.addEventListener("unload",fn,false);
} else {
window.addEventListener("onunload",fn);
}
break;
default:
Ext.fly(window).on(ev, fn);
break;
}


}
}


Anyone have a better way?

mitchellsimoens
8 Mar 2012, 3:11 PM
Your third bit of code is a better solution than the first. Sometimes more code is better.