tl;dr: I use an ajax-retrieved array of objects to generate a list of radio buttons. When a radio button is checked, I want to make compute on the selected object and save the value inside a ko.observable()
which is then shown in the HTML document via data-bind
.
Here's what I did:
Firstly, I am retrieving array of user objects (via ajax):
var ViewModel = function() {
var self = this;
// an array of retrieved user objects
self.retrievedUsers = ko.observableArray([]);
self.getUsers = function() {
$.getJSON('/retrieve-all-users', function(data) {
self.retrievedUsers(data);
});
};
};
ko.applyBindings(new ViewModel());
The retrieved array looks like this:
[{'name': 'Johnny', 'age': 20}, {'name': 'Jenny', 'age': 21}]
Then, I use this array to create radio buttons:
<form>
<!-- ko foreach: retrievedUsers -->
<input type="radio" name="people" data-bind="checkedValue: name">
<span data-bind="text: name"></span>
<!-- /ko -->
</form>
This should be rendered like this:
<form>
<input type="radio" name="users" value="Johnny"> <span>Johnny</span>
<input type="radio" name="users" value="Jenny"> <span>Jenny</span>
</form>
Goal: Whenever a radio button is checked (and a user is selected), I want to calculate the selected user's age in the upcoming year (user.age + 1) and save this computed age in an ko.observable()
.
Then, I hope to data-bind
the computed age in the template:
<div>
The selected person will be
<span data-bind="text: SelectedPersonAgeNextYear"></span>
years old in the upcoming year.
</div>
I appreciate any tips!
Another example usage: On a hotel booking website, a list of 'rooms' are shown as radio buttons. When a room is checked, a computed price is shown (price + tax + number of persons, etc).