2012-01-26 14 views
2

我是新來的燼,所以也許我做錯了。ember.js <select>由兩個不同的對象填充和選擇

我正在嘗試創建一個選擇下拉列表,其中包含從外部數據源提供的三個值。我還想根據存儲在不同模型中的值在列表中選擇正確的值。

我見過的大多數例子都處理靜態定義的下拉菜單。到目前爲止,我所擁有的是:

{{#view contentBinding="App.formValues.propertyType" valueBinding="App.property.content.propertyType" tagName="select"}} 
    {{#each content}} 
    <option {{bindAttr value="value"}}>{{label}}</option> 
    {{/each}} 
{{/view}} 

而我的模塊中:

App.formValues = {}; 
App.formValues.propertyType = Ember.ArrayProxy.create({ 
    content: [ 
     Ember.Object.create({"label":"App","value":"app", "selected": true}), 
     Ember.Object.create({"label":"Website","value":"website", "selected": false}), 
     Ember.Object.create({"label":"Mobile","value":"mobile", "selected": false}) 
    ] 
}); 

最後我對象:

App.Property = Ember.Object.extend({ 
    propertyType: "app" 
}); 

App.property = Ember.Object.create({ 
    content: App.Property.create(), 

    load: function(id) { 
     ...here be AJAX 
    } 
}); 

下拉將填充,但它的選中狀態不會反映App.property的值。我知道我錯過了一些作品,並且我需要某個人告訴我我該走什麼方向。

+0

我想你必須告訴我們你在做什麼,然後才能說任何人是否做錯了。 – Pointy

+0

@Pointy不小心碰到提前輸入,所以SO應該有「撤消提交」 –

+1

我想這可能是因爲你的聲譽得分:-) – Pointy

回答

2

答案是在formValues上使用.observes()。由於某些原因.property()會折騰一個錯誤,但.observes()不會。

我已經發布了完整的AJAX解決方案供參考,並將隨任何進一步的開發進行更新。

App.formValues = {}; 
App.formValues.propertyType = Ember.ArrayProxy.create({ 
    content: [], 

    load: function() { 
     var that = this; 

     $.ajax({ 
      url: "/api/form/propertytype", 
      dataType: "json", 
      success: function(data) { 
       that.set("content", []); 
       _.each(data, function(item) { 
        var optionValue = Ember.Object.create(item); 
        optionValue.set("selected", false); 
        that.pushObject(optionValue); 
       }); 
       that.update(); 
      } 
     }); 
    }, 

    update: function() { 
     var content = this.get("content"); 
     content.forEach(function(item) { 
      item.set("selected", (item.get("value") == App.property.content.propertyType)); 
     }); 
    }.observes("App.property.content.propertyType") 
}); 
App.formValues.propertyType.load();