[英]How to generically hook up dependent drop-downs with knockout
我有一個像下面這樣的json結構:
var scenario = {
paints: [
{
product: 'Super Paint',
sheens: [
{ sheen: 'Satin', cost: 42 },
{ sheen: 'Semi-Gloss', cost: 50 }
]
},
{
product: 'Cashmere',
sheens: [
{ sheen: 'Flat', cost: 42 },
{ sheen: 'Medium Lustre', cost: 50 }
]
}
],
walls: {
"sheen":"Flat",
"paintProduct":"Cashmere",
},
ceiling: {
"sheen":"Flat",
"paintProduct":"Cashmere",
}
};
我現在想出要使下拉列表與給定的可繪畫項目相關的方法如下:
function getSheens(paintProduct) {
if (paintProduct) {
for (var i = 0; i < self.scenario.paints.length; ++i) {
if (self.scenario.paints[i].product === paintProduct) {
return self.scenario.paints[i].sheens;
}
}
}
return null;
}
self.scenario.walls.sheens = ko.computed(function() {
return getSheens(self.scenario.walls.paintProduct());
});
self.scenario.ceiling.sheens = ko.computed(function() {
return getSheens(self.scenario.ceiling.paintProduct());
});
這是html:
<div class="item edit-walls" data-bind="with: scenario.walls">
<label>Product</label>
<select class="form-control paint-product" data-bind="options:$parent.scenario.paints, optionsText:'product', optionsValue:'product', value:paintProduct"></select>
<label>Sheen</label>
<select class="form-control paint-sheen" data-bind="options:$parent.scenario.walls.sheens, optionsText:'sheen', optionsValue:'sheen', value:sheen"></select>
</div>
給定項目的塗料產品更改應重新加載新選擇的塗料產品的光澤。
油漆產品的選擇值和項目(即牆)的光澤存儲在牆對象中。
我要避免的是針對每種不同的物料類型重復計算的淘汰賽電話。 有沒有辦法使這種情況在全球范圍內發生並以某種方式傳遞到上下文中?
我使用的是kickout.js,knockout.viewmodel.js和jQuery。
您基本上是在問是否有可能將“牆”和“天花板”標准化為一個概念。 當然可以。 我們稱它們為paintables
。 將數據結構更改為以下形式:
var scenario = {
paints: [/* omitted */],
paintables: [
{
"name":"walls",
"sheen":"Flat",
"paintProduct":"Cashmere"
},
{
"name":"ceiling",
"sheen":"Flat",
"paintProduct":"Cashmere"
}]
};
然后,您可以有一個Paintable
,它實現了你的邏輯構造函數sheen
在干燥方式秒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.