Thursday, June 30th, 2005

Code: Try.these(func1, func2, func3)

Category: JavaScript

<>p>In the “cool JavaScript snippets” department, we delve into the Prototype library for a nice function which tries to fire and forget through a set of operations.

Defining Try.these

var Try = {
  these: function() {
    var returnValue;
    
    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    
    return returnValue;
  }
}

Example using the function

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  },
  
  emptyFunction: function() {}
}

Related Content:

Posted by Dion Almaer at 2:42 pm
2 Comments

++++-
4.2 rating from 12 votes

2 Comments »

Comments feed

That code would be much easier to read with formatting!

Comment by Marc Novakowski — June 30, 2005

Cool. Basically a Chain of Responsibility. You could make it slightly more structured to allow individual handlers to reject the request in ways other than throwing an error, but I’d not really thought of using this pattern in JavaScript.

Comment by Thom Lawrence — July 1, 2005

Leave a comment

You must be logged in to post a comment.