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! :)