views:

32

answers:

2

Not sure the best way to phrase the question, but suppose you are using jQuery to setup various things like so:

<script>

    function doSecond(){
        alert("Hi");
    }

    function dofirst(){
        var x = asdasd;
    }

    $(dofirst);
    $(doSecond);

</script>

So, imagine that dofirst and dosecond are completely independent. If dofirst throws an exception, which of course it will, then doSecond will never fire. I understand why this happens, but I'm wondering if there is a way of getting around this without having to wrap EVERY kind of jQuery handler that I want to set up in a try catch. E.g., I'd rather not do:

try{
 $(doFirst);
}
catch{
 //maybe log here?
}

try{
 $(doSecond);
}
catch{
 //maybe log here?
}

Now, if you're wondering why I want to do this? Well, take for example the code on the page you're looking at right now:

<script type="text/javascript">
        $(function() {
            $('#title').focus(function() { $('#how-to-tag').hide(); $('#how-to-format').hide(); $('#how-to-title').fadeIn('slow'); });
            $('#wmd-input').focus(function() { $('#how-to-tag').hide(); $('#how-to-format').fadeIn('slow'); $('#how-to-title').hide(); });
            $('#tagnames').focus(function() { $('#how-to-tag').fadeIn('slow'); $('#how-to-format').hide(); $('#how-to-title').hide(); });
        });
    </script>

Is it really necessary to have certain dom elements fade out when you click on them? No. But if you make a mistake in that function, then quite possibly other javascript that you really, really do need to run may never get setup.

A: 

jQuery in general is pretty kind to you.
It will throw exceptions very, very rarely.

To avoid exceptions, it's up to you. Make sure all references you access are valid, check for empty objects, etc. etc., short: Write clean, solid, robust code.

Of course there are times where you need a try/catch block, but your example is certainly not one of those. Somebody could come up now with the idea to wrap all your javascript code into one big try/catch statement.
If you see anyone doing that, step back from the computer silently and run.. as fast as you can.

jAndy
A: 

A couple of ways to ensure things run independently of each other:

  • As you said, try/catch around each

  • Call each in a setTimeout (or whatever the jQuery syntactic sugar is for that)

  • Separate into different <script> blocks

jhurshman