I have the following view model which contains an array of elements
function ReservationsViewModel() {
var self = this;
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0, id = 1 },
{ mealName: "Premium (lobster)", price: 34.95, id = 2 },
{ mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
];
}
I want to bind this view model to a input, but i want to bind only the Single array element meal name that has the id value as the data-id attribute of the input.
<input type="text" id="firstElementMealName" data-id="1" data-bind="value: ??"></input>
In this example i would bind the array element with id = 1, and the text would appear as "Standard (Sandwich)", but i still need the full binding and change tracking (observables) and all the other good stuff in Knockout.
How to pick up the data-id and use it in the binding code to bind the appropriate meal to the input?
Thanks in advance
Suggested solution:
function ReservationsViewModel() {
var self = this;
self.availableMeals = ko.observableArray([
{ mealName: "Standard (sandwich)", price: 0, id = 1 },
{ mealName: "Premium (lobster)", price: 34.95, id = 2 },
{ mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
]);
self.getMealById = function(id) {
ko.utils.filterArray(self.availableMeals(), function(item) {
return item.id == id;
});
};
}
In the view:
<input type="text" id="firstElementMealName" data-bind="value: getMealById(1)"></input>
function ReservationsViewModel() {
var self = this;
self.availableMeals = ko.observable({
id_1: { mealName: "Standard (sandwich)", price: ko.observable(0) },
id_2: { mealName: "Premium (lobster)", price: ko.observable(34.95) },
id_3: { mealName: "Ultimate (whole zebra)", price: ko.observable(290) }
});
}
ko.applyBindings(new ReservationsViewModel());
In the View:
<input type="text" id="firstElementMealName" data-bind="value: availableMeals().id_2.price()"></input>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With