Exception Handling in JavaScript: Addressing Browser Incompatibilities - Assigning events to objects: using exceptions to manipulate event handlers
(Page 5 of 5 )
As I said before, JavaScript exceptions are useful enough to be applied in different conditions. Particularly when working with event handlers, exceptions can be implemented directly, in order to deal with proprietary event handling methods. Considering the above listed example, which checks for support of specific methods, it’s feasible to write a new script that utilizes exceptions to handle raised errors. Here’s what it looks like:
// Event Handler assignation using exceptions
var obj=document.getElementsByTagName('div')[0];
if(!obj){alert('Failed to get object!')};
try{
// browser is Firefox, Nestcape, etc
// use addEventListener() method
obj.addEventListener('click',processEvent,false);
}
// catch thrown error
catch(e){
try{
// browser is Internet Explorer
// use attachEvent() method
obj.attachEvent('onclick',processEvent);
}
// catch thrown error
catch(e){
alert('Failed to add event handler');
}
}
function processEvent(){
alert('Event handler successfully attached!');
}
There are several points worth mentioning about the above code. First, the script attempts to attach to the <div> element an “onclick” event handler through the “addEventListener()” method, by executing the code within a “try” block. As with XMLHTTP objects, if the code is successfully processed, the handler is tied to the proper object. Otherwise, if the attaching method is not supported by the JavaScript parser, an error will be triggered and trapped inside the corresponding “catch” block.
Returning to program flow, a new “try” block is used to attach the event handler by using the “attachEvent()” method, which is supported by Internet Explorer. Finally, if all attempts fail, a warning is displayed since no handler was successfully attached. Before I continue with the code explanation, a brief note is in order here: there is a known issue with the “addEventListener()” method for IE 5 on Mac, which fails silently when invoked, so if you’re still getting many visitors using this browser, consider using another cross-browser solution that addresses this particular case too.
By this point, hopefully you’ve understood the underlying logic of the above script, so there is plenty of room to experiment with different browser proprietary methods, for the sake of solving other incompatibilities. Of course, the whole script can be easily customized through a containing function, which would be much more useful than its current incarnation. As usual, feel free to use the above example and introduce your own improvements.
For the sake of completeness, below is the full example, which also roughly implements exceptions to attach an “onload” event handler to the “window” object:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>EXCEPTION-BASED EVENT HANDLING ASSIGNATION</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<script language="javascript">
// Event Handler assignation using exceptions
function processEvent(){
alert('Event handler successfully attached!');
}
function addEventHandler(){
var obj=document.getElementsByTagName('div')[0];
if(!obj){return false};
try{
// browser is Mozilla, Nestcape, etc.
// use addEventListener() method
obj.addEventListener('click',processEvent,false);
}
// catch thrown error
catch(e){
try{
// browser is Internet Explorer
// use attachEvent() method
obj.attachEvent('onclick',processEvent);
}
// catch thrown error
catch(e){
alert('Failed to add event handler');
}
}
}
// assign 'onload' event handler to window object
try{
window.addEventListener('load',addEventHandler,false);
}
catch(e){
try{
window.attachEvent('onload',addEventHandler);
}
catch(e){
alert('Failed to add event handler');
}
}
</script>
</head>
<body>
<div>EXAMPLEPAGE</div>
</body>
</html>
Conclusion
Finally, we’re done. Over this series I’ve discussed in detail the use of exceptions in JavaScript programs, ranging from core concepts to advanced implementation, such as multiple errors handlers, custom error object creation and practical application on form validation and cross-browser scripts.
Hopefully, the overall experience has been instructive enough for those developers that want to start out quickly using JavaScript exceptions within client-side applications. Even when exception-based programs take up some additional lines of code, giving a try is really worthwhile, due mainly to the fact that errors are handled through a more professional and robust built-in mechanism. There you have it, so take advantage of it!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |