2015-11-03 67 views
0

我有一個狀態標誌從服務器返回的數據。並在每個ItemView控件我有一些單選按鈕,如下所示:Marionette ItemView和單選按鈕

<td><input type='radio' name='<%- id %>-typeRecipe' value='0'></td> 
<td><input type='radio' name='<%- id %>-typeRecipe' value='2'></td> 
<td><input type='radio' name='<%- id %>-typeRecipe' value='1'></td> 

由於正在創建的每個ItemView控件我要檢查,如果服務器返回的狀態是相同的值作爲輸入值,即無論是0,1,或2,如果它設置該元素選擇。

Recipe = Marionette.ItemView.extend({ 
    ui: { 
    comm: 'input[type=radio]' 
}, 

onBeforeRender: function() { 
     for (var i = 0; i < this.ui.comm.length; i++) { 
     if(parseInt(this.ui.comm[i].value, 10) === this.model.get('status')) { 
      this.ui.comm[i].$el.prop('selected') 
     } 
     } 
    } 

但是,當我查看接口時,沒有一個單選按鈕檢查它們。

當我調試代碼時,我可以看到行0123¾正在執行,所以我想知道爲什麼它不顯示將元素設置爲選中?順便說一句我嘗試在onRender事件上使用該功能,但也有相同的結果

回答

1

我不同意,而不是具有onBeforeRender功能,其整體功能是檢查「狀態」並將其設置爲檢查你的方法。我會將這個「邏輯」移動到模板中,而不是在視圖中處理它。

您的範本看起來是這樣的:

<td><input type='radio' name='<%- id %>-typeRecipe' <% if (status == '0') { %>checked='checked'<% } %>value='0'></td> 
<td><input type='radio' name='<%- id %>-typeRecipe' <% if (status == '2') { %>checked='checked'<% } %>value='2'></td> 
<td><input type='radio' name='<%- id %>-typeRecipe' <% if (status == '1') { %>checked='checked'<% } %>value='1'></td> 

最後你render'er?大聲笑。只是看起來是這樣的:

this.$el.html(this.template(this.model.toJSON())); 

這又是「我的意見」,你可以處理它,你認爲合適,但我喜歡它,因爲那種世俗邏輯雜波的意見和剛剛離開身後的人閱讀比他/她更多的代碼。而且......我認爲這種方法更「優雅」,因爲你所進行的循環可以完全避免。

+1

乾杯 - 我已經開始使用你的方法,但與語法脫鉤。謝謝你讓我再次踏上正確的道路。作品一種享受 –

0

這是checked屬性的無線電輸入,而不是selected。另外,您還需要將第二個參數設置爲true,以便爲該屬性實際設置值,否則您只需獲取該值即可。

$('input.selectMe').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='radio' name='typeRecipe' value='0'> 
 
<input type='radio' name='typeRecipe' value='2' class="selectMe"> 
 
<input type='radio' name='typeRecipe' value='1'>