diff --git a/lib/OpenLayers/Util.js b/lib/OpenLayers/Util.js index 33f81102d7..695d10095e 100644 --- a/lib/OpenLayers/Util.js +++ b/lib/OpenLayers/Util.js @@ -543,10 +543,21 @@ OpenLayers.Util.getImagesLocation = function() { /** * Function: Try + * Execute functions until one of them doesn't throw an error. + * Capitalized because "try" is a reserved word in JavaScript. + * Taken directly from OpenLayers.Util.Try() * + * Parameters: + * [*] - {Function} Any number of parameters may be passed to Try() + * It will attempt to execute each of them until one of them + * successfully executes. + * If none executes successfully, returns null. + * + * Return: + * {*} The value returned by the first successfully executed function. */ OpenLayers.Util.Try = function() { - var returnValue; + var returnValue = null; for (var i = 0; i < arguments.length; i++) { var lambda = arguments[i]; diff --git a/tests/test_Util.html b/tests/test_Util.html index 04c1cd3836..4f87dc9949 100644 --- a/tests/test_Util.html +++ b/tests/test_Util.html @@ -603,6 +603,39 @@ t.eq(destination.toString(), "source", "extend properly sets custom toString method"); } + + function test_XX_Util_Try(t) { + t.plan(7); + + var func1 = function() { + t.ok(true, "func1 executed"); + throw "error"; + } + + var func2 = function() { + t.ok(true, "func2 executed"); + throw "error"; + } + + g_TestVal3 = {}; + var func3 = function() { + t.ok(true, "func3 executed"); + return g_TestVal3; + } + + g_TestVal4 = {}; + var func4 = function() { + t.fail("func4 should *not* be executed"); + return g_TestVal4; + } + + var ret = OpenLayers.Util.Try(func1, func2); + t.ok(ret == null, "if all functions throw exceptions, null returned"); + + var ret = OpenLayers.Util.Try(func1, func2, func3, func4); + t.ok(ret == g_TestVal3, "try returns first sucessfully executed function's return"); + + } // -->