2012-02-28 58 views
0

我只是潛入Ember。我正在尋找一種方法來傳遞一個普通的香草對象數組到一個集合/控制器,並讓他們輸入到正確的模型。將香草物體自動澆鑄到灰燼物體上

這裏的簡單集合視圖:

{{#collection id="prods" contentBinding="Vix.prodsController" tagName="ul"}} 
    {{content.title}} 
{{/collection}} 

這裏的模型:

Vix.Prod = Ember.Object.extend({ 
    id: null, 
    title: null 
}); 

而且控制器:

Vix.prodsController = Ember.ArrayController.create({ 
    content: [] 
}); 

然後讓我們從服務器得到一些JSON格式的數據。在這個例子中,我只是硬編碼它:

var prods = [{id:"yermom1", title:"yermom 1"}, {id:"yermom2", title:"yermom 2"}] 

Vix.prodsController.set('content', prods); 

到目前爲止好。我收到了我期望的顯示標題的li元素的簡單列表。但是,當我想更新的對象之一的稱號,使用:

Vix.prodsController.objectAt(0).set('title', 'new title') 

它抱怨,因爲對象沒有set method--它沒有被正確地投給我Vix.Prod灰燼對象。

使用這種替代:

Vix.prodsController.pushObjects(prods); 

產生相同的結果。這只是如果我明確地創建,我得到了get/set善新模型實例:

var prods = [Vix.Prod.create({id:"yermom1", title:"yermom 1"}), {Vix.Prod.create(id:"yermom2", title:"yermom 2"})] 

是否有自動類型轉換的香草對象我Vix.Prod灰燼對象的方法嗎?如果不是,我是唯一真正想要類似的東西嗎?在Backbone中,可以在集合上設置model屬性。我想我可以在我的控制器上創建一個setter來做類似的事情,只是想知道是否有內置的東西我不見了。謝謝!

回答

2

沒有魔力。我建議做一個循環包裝模型。

var prods = [{id:"yermom1", title:"yermom 1"}, {id:"yermom2", title:"yermom 2"}]; 

for (var i = 0; i < prods.length; i++) { 
    prods[i] = Vix.Prod.create(prods[i]); 
} 
+0

這似乎不工作了。當我嘗試這個時,我得到'你不應該在模型上調用'創建'。相反,用你想設置的屬性調用'store.createRecord' – 2014-10-23 04:05:41

1

如果我儘可能使用餘燼,我會想要一個快捷方式。所以這就是我現在所做的。我創造,我用它來創建我的收藏/控制器的基集合類:

Vix.Collection = Ember.ArrayController.extend({ 

    model: null, 

    pushObject: function(obj) { 
    if (this.get('model') && obj.__proto__.constructor !== this.get('model')) { 
     obj = this.get('model').create(obj); 
    }  
    return this._super(obj); 
    }, 

    pushObjects: function(objs) { 
    if (this.get('model')) { 
     objs = this._typecastArray(objs) 
    } 
    return this._super(objs); 
    }, 

    set: function(prop, val) { 
    if (prop === 'content' && this.get('model')) { 
     val = this._typecastArray(val); 
    } 
    return this._super(prop, val); 
    }, 

    _typecastArray: function(objs) { 
    var typecasted = []; 
    objs.forEach(function(obj){ 
     if (obj.__proto__.constructor !== this.get('model')) { 
     obj = this.get('model').create(obj); 
     } 
     typecasted.push(obj); 
    }, this); 
    return typecasted; 
    } 

}) 

現在,當我打電話pushObjectpushObjects.set('collection', data),如果集合實例有一個定義model屬性和對象被添加到收集不是那種類型的,他們會被施放。到目前爲止工作得很好,但我歡迎任何反饋。

0

你應該看看燼數據:https://github.com/emberjs/data

這似乎滿足您的需求...

截至今天,它尚未投入生產(如自述說明),但由於積極的發展,正在迅速趨於成熟。