答案 0 :(得分:3)
使用一个函数onChange
,然后根据selectedMeal
的值调用其他函数。
例如:
function ReservationsViewModel() {
var self = this;
self.availableMeals = ko.observableArray(
[{
name: "Standard (sandwich)",
value: 0
}, {
name: "Premium (lobster)",
value: 34.95
}, {
name: "Ultimate (whole zebra)",
value: 290
}]
);
self.selectedMeal = ko.observable(self.availableMeals()[0]);
self.onChange = function() {
switch (self.selectedMeal()) {
case 0:
self.sandwichSelected();
break;
case 34.95:
self.lobsterSelected();
break;
case 290:
self.zebraSelected();
break;
}
};
self.sandwichSelected = function() {
alert("for sandwich");
};
self.lobsterSelected = function() {
alert("for lobster");
};
self.zebraSelected = function() {
alert("for whole zebra");
};
}
ko.applyBindings(new ReservationsViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>With every selection change I want a different function to be called</p>
<select data-bind="options: availableMeals, optionsText: 'name', value: selectedMeal, optionsValue: 'value', event: {change: onChange}">
</select>