views:

62

answers:

2

Hey Team, I'm playing around with different JS design patterns, and im trying to modify some samples I've seen out there. I saw an example of a xhr factory, that had several nested try/catch statements that were nested within eachother.

try{
...
}catch(e){
    try{
    ...
    }catch(e){}
}

I figured I'd be able to do a self-invoking function. However It seems to have eluded me as to how it should work. Does anyone have any advice?

Example:
http://jsfiddle.net/jiggliemon/a7xWq/2/


[Update]:
http://jsfiddle.net/jiggliemon/b5LaZ/embedded/
Case Closed.

A: 

Changed try loop to:

for(var i = 0, l = instances.length; i < l; i ++) {
    try{
        var obj = instances[i].getInstance();
        return instances[i];
    }catch(e){ }
}

Full code

fantactuka
A: 
var XHR = (function(){
    var ins = [
        function(){return new XMLHttpRequest();},
        function(){return new ActiveXObject('Msxml2.XMLHTTP');},
        function(){return new ActiveXObject('Microsoft.XMLHTTP');}
    ],i,tmp;

    return (function tryIns(i){
        i = i || 0;
        while(i < ins.length){
            try{tmp = ins[i]();}
            catch(e){i++; tryIns(i);}
            finally{return ins[i];}
        }
        throw new Error("Your browser doesn\'t support Ajax requests");
    })();
})();
Chase