2016-05-24 30 views
0

有一個關於Ember Observers的問題以及如何使用它們。我對Ember很新,所以如果我的知識尚未到位,請原諒我。 我遇到的問題是,我想根據從下拉菜單中選擇一個簡單的文本字段來填充特定的電子郵件地址。我在prepopulatedCounties數組中存儲了一個值,但不知道如何根據該值將email-address設置爲文本字段。根據更改後的選擇下拉列表觸發觀察者 - Ember.js

JS代碼我有(APP/routes.demo.js):

export default Ember.Route.extend({ 

    model() { 
    var prepopulatedCounties = Ember.A(); 
    prepopulatedCounties.pushObject(Ember.Object.create({ value: "1", display: "Charlotte" })); 
    prepopulatedCounties.pushObject(Ember.Object.create({ value: "2", display: "Collier" })); 
    prepopulatedCounties.pushObject(Ember.Object.create({ value: "3", display: "Hillsborough" })); 
    prepopulatedCounties.pushObject(Ember.Object.create({ value: "4", display: "Lee" })); 
    prepopulatedCounties.pushObject(Ember.Object.create({ value: "5", display: "Manatee" })); 

return Ember.Object.create({ 
    counties  : prepopulatedCounties, 
    selectedCounty : undefined, 
    email   : undefined, 
}); 
    }, 


actions: { 
setEmail() { 
     var dataValue = this.get('currentModel.selectedCounty'); 

     if(dataValue==="1"){ 
      this.set('currentModel.email', "[email protected]"); 
     } 
     else if(dataValue==="2"){ 
      this.set('currentModel.email', "[email protected]"); 
     } 
     else if (dataValue==="3"){ 
      this.set('currentModel.email', "[email protected]"); 
     } 
     else if (dataValue==="4"){ 
      this.set('currentModel.email', "[email protected]"); 
     } 
     else if (dataValue==="5"){ 
      this.set('currentModel.email', "[email protected]"); 
     } 
     else{ 
      this.set('currentModel.email', "None Selected"); 
     } 
    } 

的HTML代碼我有(應用程序/模板/ demo.hsb):

<div> 
     <br> 
     Email: 
     <br> 
     {{input type="text" id="mail" value=model.email readonly='readonly'}} 
    </div> 
    <div> 
     <br> 
     Counties: 
     <br> 

     <select {{action 'setEmail' on='change'}}> 
     {{#x-select value=model.selectedCounty as |xs|}} 
      {{#xs.option value="0"}}Choose One{{/xs.option}} 
      {{#each model.counties as |county|}} 
      {{#xs.option value=county.value}}{{ county.display }}{{/xs.option}} 
      {{/each}} 
     {{/x-select}} 
     </select> 
    </div> 

我沒有正確設置setEmail操作,因爲當我最近添加<select {{action 'setEmail' on='change'}}>行時,下拉菜單停止工作,因爲我確信我沒有正確操作。我正在尋找一種方法來完成這項工作,並且我讀過Ember Observers將是一個很好的方法,但我還沒有弄清楚如何利用觀察者,所以有些人會幫助完成這項工作。在這種情況下,將不勝感激!

回答

2

處理Ember(v1.13或更新版本)中的選擇選項有更簡單的方法。

我刪除了值字段,並直接將電子郵件添加到您的對象,您可以在此處看到它在這個Ember旋轉。

https://ember-twiddle.com/d49b18538aca70dafcb5d9070eb6a98c?fileTreeShown=false&numColumns=3&openFiles=routes.application.js%2Croutes.application.js%2Ccontrollers.application.js

+0

我很感謝@Payam的迴應!是的,這看起來更簡單。 – LearningJS888

相關問題