2015-01-02 35 views
0

我有一個期望將參數作爲對象數組的參數。 默認情況下,該參數將是一個本地數組,其中包含本機對象。 我想將此數組轉換爲包含餘燼對象的餘燼數組。將本機數組/對象轉換爲Ember.Array/Ember.Object的最佳實踐

我在想這樣的事情,但是這將創建一個無限循環,每次射擊觀察員:

export default Ember.Component.extend({ 
    content: null, 

    contentDidChange: function() { 
     var content = Ember.A(); 
     this.get('content').forEach(function (item) { 
      content.addObject((item.constructor.toString() !== 'Ember.Object') ? Ember.Object.create(item) : item); 
     }); 
     this.set('content', content); 
    }.observes('content'), 
}); 

什麼是做到這一點的最佳做法?

感謝

回答

1

你可以只修改初始參數當組件第一次啓動時對didInsertElement像這樣:

App.ArrContentComponent = Ember.Component.extend({ 
    content: null, 

    modifyContent: function(){ 
    var content = this.get('content').map(function(item){ 
     return Ember.Object.create({ name: item }); 
    }); 

    this.set('content', content); 
    }.on('didInsertElement') 
}); 

工作實例here

+0

如果內容發生變化,這將不起作用。 – Asgaroth

1

如果你爲什麼需要內部對象的原因,你的組件是因爲你在做this.get(..,那麼你可以通過使用Ember.get(..代替。

如果不是這種情況,那麼我會建議將組件綁定到轉換後的屬性,而不是原始的content

transformedContent: null, 
makeItem: function(item) { 
    return Ember.Object.create(item); 
}), 
cloneItems: function() { 
    this.set('transformedContent', this.get('content').map(this.makeItem)); 
}.observes('content'), 

如果你想最佳實踐,然後我會創造一個computed array,是因爲他們來來去去,你將能夠重新使用轉換的項目。

transformedContent: App.computed.objectArray('content')