我前段时间关注了Knockout教程,其中一个是其中之一 http://learn.knockoutjs.com/#/?tutorial=collections
详细介绍了如何创建列表和集合。 但是我想在列表中创建一个级联下拉选择。
我的问题可能是你可以使用淘汰赛在动态列表中创建一个级联下拉列表吗?
实际上,经过几个小时的研究,我实际上设法解决了这个问题,所以我会在这里添加它作为答案,因为我觉得它对某些人有用。也许还有更好的方法吗?
答案 0 :(得分:2)
它会起作用,但我只想添加一件事:小缓存。基本上,一旦你加载了可用于特定餐食的餐点,你就可以在你的餐食对象中创建一个属性来存储它们。这样,随后的电话可能知道这些餐食已经装好了。我为此创建了一个可观察的数组,如下所示:
鉴于此函数模拟从服务器检索数据:
var mealTypesByKey = [];
mealTypesByKey[1] = [{ mealName: "Vegemite Sandwich", price: 4.00, mealType: 1},
{ mealName: "Cheese Sandwich", price: 34.95,mealType: 2 },
{ mealName: "Jam Sandwich", price: 290, mealType: 3 } ];
mealTypesByKey[2] = [{ mealName: "Standard (Ham)", price: 15, mealType: 1},
{ mealName: "Chicken Wrap (Possibly rat)", price: 15, mealType: 1} ];
mealTypesByKey[3] = [{ mealName: "Premium (lobster)", price: 34.95,mealType: 2 },
{ mealName: "Ultimate (whole zebra)", price: 290, mealType: 3 } ];
function serverGetMealsForType(key) {
return mealTypesByKey[key];
}
您可以定义以下可订阅功能:
self.mealType.subscribe(function(newMealType) {
if(!newMealType.meals) {
newMealType.meals = ko.observableArray([]);
newMealType.meals(serverGetMealsForType(newMealType.key));
console.log("meals loaded");
} else {
console.log("meals already available for meal type " + newMealType.key);
}
});
这样,动态列表可以使用给定的绑定正确地重新创建:
<td><select data-bind="options: mealType().meals, value: meal, optionsText: 'mealName'"></select></td>
这是避免不必要的服务器调用的常用且简单的技术。
修改:忘记添加fiddle I've forked。
答案 1 :(得分:1)
我从learn.knockoutjs.com上获取了原始版本的馆藏教程。 我决定添加一种膳食类型选择,在选择时改变可用的膳食。
我发现进入单个列表项目所需的可用餐点,因为它将改变每个
function SeatReservation(name, initialMeal, initialMealType) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
// Non-editable catalog data - would come from the server
self.availableMeals = ko.observableArray([
{ mealName: "Standard (sandwich)", price: 0, mealType: 1},
{ mealName: "Premium (lobster)", price: 34.95,mealType: 2 },
{ mealName: "Ultimate (whole zebra)", price: 290, mealType: 3 }
]);
我也在个人预订中创建了一种膳食类型:
self.mealType= ko.observable();
然后列出可用的膳食类型:
// Non-editable catalog data - would come from the server
self.availableMealTypes = [
{ mealTypeName: "Vege", key: 1 },
{ mealTypeName: "Dead Animal", key: 2 },
{ mealTypeName: "Meat Whore", key: 3}
];
然后绑定到HTML中。
最后,我订阅了膳食类型的变化,并修改了此功能中可用的膳食收集:
self.mealType.subscribe(function() {
if (self.mealType().key == 1)
{
self.availableMeals ([
{ mealName: "Vegemite Sandwich", price: 4.00, mealType: 1},
{ mealName: "Cheese Sandwich", price: 34.95,mealType: 2 },
{ mealName: "Jam Sandwich", price: 290, mealType: 3 } ]);
}
最终完整的解决方案可以在this jsFiddle中找到。