views:

71

answers:

4

For example:

> function foo() {
>    jQuery(whatever).each( function() {
         return; // this just exits the anonymous function - is there a way to return from foo?
     }
   );
> 
> }
+1  A: 

The function can return false.

edit oh ha ha, the "from foo" was scrolled off the right side :)

To do that, you could use try/catch

function foo() {
  try {
    jQuery('whatever').each(function() {
      if (noMoreFoo()) throw "go";
    });
  }
  catch (flag) {
    if (flag === "go") return;
    throw flag;
  }
}
Pointy
+3  A: 

*Correction: Added more detail. Use a flag to allow returning from the PARENT function *

function foo() {
   var doreturn = false;
   jQuery(whatever).each( function() {
     if(youwanttoreturn){
         doreturn=1;
         return false;
     }
   });
   if(doreturn)return;
}

http://api.jquery.com/each/ "We can stop the loop from within the callback function by returning false."

Lee
He wants to return from "foo"!
Pointy
A: 

Not really. This will ghetto do what you want (i think):

function foo() {
    var bar=null;
    $(whatever).each( function() {
        bar="bar";
        return false;
    }); 
    return bar;
}
var fooResults = foo();
David Murdoch
A: 
function foo() {
    $result = false;
    jQuery(whatever).each( function() {
            $result = true;
    });
    // We will reach this point after the loop is over.
    return $result;
}
Ivo Sabev
?? I don't think that'll do anything at all; it's just like `return` with no value as far as jQuery is concerned.
Pointy
@Pointy Thanks, corrected.
Ivo Sabev