2012-04-04 111 views
0

我已經讀了所有的測試兩次,文檔三次,我仍然不確定如何使用Ember。選擇正確的方式。我有我認爲是一個非常簡單的情況:Ember.Select沒有正確設置默認值

我有一個模型對象(goal_type)中的字符串值,我想要雙向綁定到一個選擇,並選擇默認值爲goal_type字段的起始值。幾個問題:

  1. 我無法獲得select以接受模型的初始goal_type。
  2. 所有這些看起來太複雜 - 必須有一個更簡單的方法來做到這一點,而不是設置觀察者來修改原始控制器的狀態。

幫助 - 我瘋了試圖弄清楚這一點。

 
Azul.goalController = Ember.Object.create({ 

    loadGoal: function(data) { 
     this.set('content', Azul.store.loadAll(Azul.Goal, data)); 
    }, 

    newGoal: function() { 
     goal = Azul.store.createRecord(Azul.Goal, {goal_type: "type2"}); 
     this.set('content', goal); 
     Azul.selectedGoalTypeController.selectGoalType(goal.get('goal_type')); 
    } 

    }); 

    Azul.selectedGoalTypeController = Ember.Object.create({ 
     selectedGoalType: null, 

     selectedGoalTypeChanged: function() { 
     Azul.goalController.content.set('goal_type', this.selectedGoalType.value); 
     }.observes('selectedGoalType'), 

     selectGoalType: function(goal_type) { 
     Azul.goalTypesController.content.forEach(function(item, index, self) { 
      if (goal_type == item.value) { 
       self.set('selectedGoalType', item); 
      } 
     }); 
     } 
    }); 

    Azul.goalTypesController = Ember.ArrayController.create({ 
     content: [ 
      {value: 'type1', label: 'Type 1'}, 
      {value: 'type2', label: 'Type 2'} 
     ] 
    }); 

回答

1

您必須將值設置爲與選擇選項綁定的對象,而不是值。 這裏:

Azul.selectedGoalTypeController.selectGoalType(goal.get('goal_type')); 

只要做到:

Azul.selectedGoalTypeController.set('selectedGoalType', goal); 

順便說一句,你的問題似乎有點迷惑。對不起,如果我誤解了你。 我做了一個簡單的示例如何使用選擇,這裏是小提琴:http://jsfiddle.net/Qpkz5/300/

+0

我瞭解您的示例,但我在尋找什麼是建議的方式綁定模型上的字段值選擇並使模型上的字段值設置爲選擇的默認值。我不太確定我是否理解這種做法的餘燼。 – outside2344 2012-04-04 22:58:13

+0

我更新了小提琴,檢查是否有助於更多... – Luan 2012-04-05 10:53:39