Freelancer's Playground! Learn Programming, The Freelancer's Way

1Feb/070

Using Try.these to make your javascript code robust

Hi there, this is yet another prototype tutorial. Today well learn a simple way to avoid error in our javascript code. We'll use Try.these method of prototype framework. So, how do we do this? First, we need to call the prototype library.

<script src="prototype-1.4.0.js" mce_src="prototype-1.4.0.js" type="text/javascript" language="javascript"></script>

Now, we'll create function that use Try.these.

<script>
<script>
function getData(){
    return Try.these(
        function(){return $('this-should-error').innerHTML;},
        function(){return $('this-return-error-too').innerHTML;},
        function(){return 'this is default data';}
    );
}
</script>

As you can see in the example above, using Try.these is very straight forward. Try.these will return data from the first function that not return undefined or null. If all argument return error then Try.these will return error value from the last argument.

blog comments powered by Disqus