2015-09-22 33 views
1

我試圖設置一個簡單的Marionette's CompositeView。這就是我想要的到底是:Marionette CompositeView中的select>選項上下文

%select#target-id 
    %option{:value => "#{@id}"} = @name 
    %option{:value => "#{@id}"} = @name 
    etc 

在我CompositeView我指定的childViewContainer: select,我需要在此選擇的選項,以顯示兩個@name(用於可讀性)和@id(對於相關事件) 。由於默認的div元素的性質,我可以給speficfy tagNameoptionItemView

class New.TargetView extends App.Views.ItemView 
    template: "path/to/template" 
    tagName: 'option' 

而且在模板中,我可以通過只待創建選項元素的內容:= @name。這可以正常工作,Marionette爲每個模型創建一個選項元素,並使用模型的名稱填充它。問題是我不知道如何傳遞屬性,因爲我無法指定尚未創建的元素的屬性。

我也試圖在ItemView這樣設置attributes屬性:

attributes: 
    value: "#{@id}" 

它在技術上的工作原理:該選項填入value=""屬性,但內容是不確定的。請指教。

回答

1

我不太確定使用attributes的部件。您應該傳遞散列或函數,以便返回散列,如Backbone view.attributes docs中所述。

attributes: 
    value: "#{@id}" 

在舊金錢它的作品是這樣的。這裏是jsfiddle

attributes: function() { 
    return { 
     value: this.model.id 
    }; 
} 
+0

我已經設法通過使用'@ $ el.unwrap()'強制展開元素來解決問題,但是這樣更加清晰,並且一直很明顯。非常感謝! –

0

CompositeViewItemView分別是需要木偶集合和模型的意見。當您創建CompositeView時,您會傳遞一組模型,其中每個模型都將傳遞給相應的ItemView

我的猜測是,它不是模板的問題,但與您如何設置數據。據我所知,ItemView沒有attributes選項,你必須用正確形成的集合初始化CompositeView,或在ItemView上用serializeData方法創建新屬性。

在第一種情況下,你會做這樣的事情:

var SomeCompositeView = Marionette.CompositeView.extend({ 
    template: "your-template-name", 
    childViewContainer: select 
}); 

var SomeItemView = Marionette.ItemView.extend({ 
    template: "your-other-template", 
    tagName: 'option' 
}); 

// This collection can be retrieved from a database or anywhere else 
// Just make sure that the models have the fields you want 
var myCollection = new Backbone.Collection([{id: "someid1", name: "name1"}, {id: "someid2", name: "name2"}]); 

var view = new SomeCompositeView({collection: myCollection}); 

在第二種情況下,你將有類似的東西,但是,ItemView你必須:

var SomeItemView = Marionette.ItemView.extend({ 
    template: "your-other-template", 
    tagName: 'option', 
    serializeData: function() { 
     return { someAttribute: "someValue" } 
    } 
} 

剛請記住,對於第二種方法,ItemView必須有權訪問您要返回的值。 serializeData僅用於重新格式化數據或對無法在模板上執行的數據執行操作。該模板只能訪問您從serializeData返回的變量,與原始模型無關。

+0

謝謝您的回覆。本身沒有問題,一切都像它應該的那樣工作。我可以在我的ItemView模板中編寫'%option {:value =>「#{@ id}」} = @ name',@id和@name將被正確解析和顯示。然而,在這種情況下,每個'%option {:value =>「#{@ id}」} = @ name'將被包裹在由Marionette創建的'div'中,這會破壞'slecect> options' HTML結構。所以我需要找到在_single_元素中傳遞content _and_屬性的方法。 –

+0

這聽起來很奇怪。你可以添加剩下的代碼(創建集合的地方,如何將它傳遞給視圖等)?此外,在你原來的問題中,你沒有提到任何有關'div'的包裝,但是這也聽起來像你的代碼有問題,因爲如果你爲這兩個視圖提供'tagName',它不應該創建一個'div'。 – JayC

相關問題