Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs: best way to iterate through ArrayProxy content?

Tags:

ember.js

Often, I need to loop through an Ember.ArrayProxy object's content.

Exemple 1, I need to build a list of IDs:

var loc = myArrayProxy.get('length') || 0,
    ids = new Array(),
    idsList;

while(--loc >= 0) {
    var curObject = myArrayProxy.objectAt(loc);
    ids.push(curObject.id);
}
idsList = ids.join(',');

Exemple 2, I need to build an Array of primitive objects (not Ember.Object):

var loc = myArrayProxy.get('length') || 0,
    newContent = new Array();

while(--loc >= 0) {
    var curObject = myArrayProxy.objectAt(loc);
    newContent.push({
                      id:   curObject.id,
                      name: curObject.name
                   });
}

Question: is there a better way to do this? The "while(--loc >= 0)" seems bad to me.

like image 301
Florent Jaouali Avatar asked Jul 04 '12 06:07

Florent Jaouali


1 Answers

Ember.ArrayProxy provides many friendly functions (through Ember.Array, Ember.Enumerable, ...). Loops can often be avoided using "forEach". In your 2nd example, you may consider using "map". Here is a link to Ember.ArrayProxy documentation. Be sure to look at: Ember.Array and Ember.Enumerable

edit:

For instance, assuming the order of the ids is not relevant, your first example could be written:

var idsList = myArrayProxy.mapProperty('id').join(',');
like image 113
Stéphane Blond Avatar answered Oct 22 '22 08:10

Stéphane Blond