2012-06-07 81 views
7

從json對象數組中創建一個餘燼對象數組的最佳方式是什麼?Ember.js如何加載簡單的餘燼對象數組

我可以這樣每個單獨的對象上使用setProperties方法:

var ret = Ember.A(); 

pojos.forEach(function(obj){ 
    var em = Ember.Object.create({}); 
    emCluster.setProperties(obj); 
    ret.push(emCluster); 
}); 

但有獲得相同結果的一個行的方式?

回答

7

我倒是map而不是使用forEach

pojos.map(function(obj){ 
    return Ember.Object.create().setProperties(obj); 
}); 
+0

有沒有辦法遍歷對象? – NkS

1

沒錯:

var ret = pojos.map(function(data) { return Ember.Object.create(data); }); 
+0

這不會有同樣的結果。 'create'與'setProperties'有不同的含義。 – ebryn

+0

沒錯,但沒有完整的上下文,不確定它會產生很大的不同,因爲我們不知道這些對象是否會被綁定。如果是這樣,管理費用將在約束時支付。但有趣的是,這種微妙的差異被強調了。 THKS。 :) –

+0

其實,主要的區別是,如果你使用setProperties計算屬性設置器將被調用。隨着創建,他們會被覆蓋。 – ebryn

0

我用這個在我的訓練應用程序從遠程服務器獲取JSON並將其解析到對象數組。

App.Model.reopenClass({ 
    allItems: [], 
    find: function(){ 
    $.ajax({ 
     url: 'http://remote_address/models.json', 
     dataType: 'json', 
     context: this, 
     success: function(data){ 
     data.forEach(function(model){ 
      this.allItems.addObject(App.Model.create(model)) <------------------- 
     }, this) 
     } 
    }) 
    return this.allItems; 
    }, 
}); 
0
ret = (Em.Object.create pojo for pojo in pojos)