问题
I've come across a piece of code that I'd like to model. However, I just have a few questions and perhaps you guys can help. Here's the code:
function addEvent( brw_obj, type, func ) {
if (brw_obj.addEventListener) { // all browsers except IE < v9
brw_obj.addEventListener( type, func, false );
} else if (brw_obj.attachEvent) { // IE only for v < v9
brw_obj["e"+type+func] = func;
brw_obj[type+func] = function() {
brw_obj["e"+type+func]( window.event );
}
brw_obj.attachEvent( "on"+type, brw_obj[type+func] );
}
/* else if (brw_obj.captureEvents) {
brw_obj.captureEvents(Event.CLICK); // only works with FF < v3!
}
*/
}
Now, I understand somewhat that the code is checking for addEventListener or attachEvent; but what do the following lines mean in detail? I've haven't seen javascript written like this:
brw_obj["e"+type+func] = func;
brw_obj[type+func] = function() {
brw_obj["e"+type+func]( window.event );
}
brw_obj.attachEvent( "on"+type, brw_obj[type+func] );
Also, is using this code a good way of doing browser or object detection?
I'm writing a script and need to be sure it runs on all modern browsers as well as old ones. From what I understand, most modern browsers support addEventListener and IE supports attachEvent. What I'm not sure is if older browsers support either.
As far as the commented-out lines:
/* else if (brw_obj.captureEvents) {
brw_obj.captureEvents(Event.CLICK); // only works with FF
}
*/
I read somewhere that captureEvents is only supported by older Firefox browsers. In the context of the entire code, are these lines needed?
Any and all insightful comments, critiques, and advice is welcome. Thanks! :)
回答1:
I have been using the try/catch approach for a while and it's been working just fine for my current projects. Please have a look at the following code snippet:
var request;
try {
request = new XMLHttpRequest(); // standard
}
catch (e) {
request = new ActiveXObject("Microsoft.XMLHTTP"); // workaround
}
The above sample should work on all browsers back to Internet Explorer 5.0; Of course, you can't support all ancient browsers, but hey, Mosaic didn't talk JavaScript, anyway.
So, you could "try" to call addEventListener and if you "catch" an error you could then call attachEvent.
Just my $0,02.
I've recently faced the addEventListener issue myself, so here's my current approach on the matter:
function addEventListener(target, type, listener) {
if (target) {
if (target.addEventListener) {
target.addEventListener(type, listener, false);
}
else if (target.attachEvent) {
target.attachEvent("on" + type, listener);
}
}
else {
throw new Error("Can't addEventListener: target object is null.");
}
}
Then you just call the new addEventListener function, which carries away with whatever the browser supports.
来源:https://stackoverflow.com/questions/8436736/addeventlistener-code-snippet-translation-and-usage-for-cross-browser-detectioin