views:

57

answers:

2

I have a Prototype class - within the class i call a function and within this function i do en enumerable.each iteration. If an element within this iteration fails a check i then call another function which then re-calls this same function later. Can i break within this iteration so not only the iteration is ended but nothing else within the function is called.

Say with this code i wouldnt want the console.log to be called if elm.something == 'whatever'. Obviously i could set a variable and then check for this after the function but is there something else that i should be doing?

myFunction: function(el){
    el.each(function(elm){ 
        if(elm.something == 'whatever'){
            this.someOtherFunction(elm);
        }
    },this);            
    console.log("i dont want this called if elm.something == 'whatever'");
}

Just to be clear, in this case the console.log is just placeholder code for the beginnings of some additional logic that would get executed after this loop

+2  A: 

The simplest way would be to avoid using each() and instead rewrite using a for loop:

myFunction: function(el){
    for(var i in el) {
      var elm = el[i];
        if(elm.something == 'whatever'){
            return this.someOtherFunction(elm);
        }
    }
    console.log("i dont want this called if elm.something == 'whatever'");
}
twerq
+2  A: 

You answered it yourself "Obviously i could set a variable and then check for this after the function"

In this case, you're basically looking to not call the console.log even if elm.something == 'whatever' for a single 'elm'

myFunction: function(el){
    var logIt = true;
    el.each(function(elm){ 
        if(elm.something == 'whatever'){
            logIt = false;
            this.someOtherFunction(elm);
        }
    },this);            
    logIt && console.log("i dont want this called if elm.something == 'whatever'");
}
selvin