0
我想要做的是從一些其他更大的可用項目列表(針對上下文認爲指定某種類型的產品的成分)建立項目列表。在Knockout方面,我仍然非常綠,並且想知道我是否缺少了一些東西,因爲我目前使用的解決方案感覺不對。我有幾個相當標準的模板,我正在使用foreach綁定我的視圖模型上的兩個可觀察數組(一個用於可用成分列表,另一個用於產品選定成分列表)。Knockout JS建立項目列表
<div data-bind="template: {name:'ingredientTypeTemplate', foreach: ingredientTypes}"></div>
<div data-bind="template: {name:'selectedIngredientTypeTemplate', foreach: selectedIngredientTypes}"></div>
<script>
var productTypeViewModel = {
ingredientTypes: ko.observableArray([]),
selectedIngredientTypes: ko.observableArray([]),
addIngredient: function() {
productTypeViewModel.ingredientTypes.remove(this);
productTypeViewModel.selectedIngredientTypes.push(this);
},
removeIngredient: function() {
productTypeViewModel.selectedIngredientTypes.remove(this);
productTypeViewModel.ingredientTypes.push(this);
},
};
$(document).ready(function() {
$.getJSON("/IngredientType/Index")
.success(function (data) {
productTypeViewModel.ingredientTypes($.parseJSON(data));
})
.error(function() { alert("error"); });
ko.applyBindings(productTypeViewModel);
});
</script>
<script type="text/x-jquery-tmpl" id="ingredientTypeTemplate">
<div>
<span>${Name}</span>
<a href='#' data-bind="click: productTypeViewModel.addIngredient">Add</a>
</div>
</script>
這是最好的方式來做我想用Knockout做什麼?雖然我不確定是什麼,但有些東西感覺不對。我確實有一個單獨的VM定義,它有一個添加函數。可以使用這種類型的虛擬機數組來初始化ingredientTypes observable,然後模板只使用data-bind「click:add」,但我不喜歡必須從這個虛擬機與主虛擬機進行通信處理點擊。
基本上我只是想說明我所做的是標準方法還是有更好的(更適合Knockout)方法。