Reputation: 997
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
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
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
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
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