PJC
PJC

Reputation: 997

EmberJS: is it possible to break from forEach?

Is there a way to break from the forEach iterator in Ember?

I tried to return false in the callback (a la jQuery) but it does not work.

Thanks! PJ

Upvotes: 7

Views: 6239

Answers (5)

Jim Hall
Jim Hall

Reputation: 7229

Using toArray can potentially remove the order of the array, which sort of defeats the purpose. You could use a normal for loop but use objectAt to make it work for you.

var emberArray = [ ... Array of Ember objects ... ],
    min = 3,
    max = emberArray.get('length'),
    targetObject;

for( var i = min; i < max; i++ ){
    targetObject = emberArray.objectAt( i );

    if( targetObject.get('breakHere') ) {
        break;
    }
}

This has the added benefit of allowing you to start at a certain index, so you can loop through the smallest number of items.

Upvotes: 0

aceofspades
aceofspades

Reputation: 7586

Use Array#find and return true to break out of the loop.

Upvotes: 0

ThomasDurin
ThomasDurin

Reputation: 2003

You can use Array#some or Array#every

[1,2,3].some(function(element) {
    return true; // Break the loop
});

[1,2,3].every(function(element) {
    return false; // Break the loop
});

More informations here

Upvotes: 13

pjlammertyn
pjlammertyn

Reputation: 989

Nope, I dont think so cfr James, looking at the foreach code, you can see that it uses a for loop under the hood. You can throw an exception, but thats like writing spagetti code. But it might be possible, you can do a feature request at github? Or write your own implementation that breaks in the for loop.

Upvotes: 0

James A. Rosen
James A. Rosen

Reputation: 65252

Ember uses the native Array.prototype.forEach if it's available, and emulates it if not. See https://github.com/emberjs/ember.js/blob/v1.0.0-rc.1/packages/ember-metal/lib/array.js#L45.

JavaScript's forEach doesn't support breaking. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach

Upvotes: 7

Related Questions