ko.js: Dynamically generated radio buttons and 

2019-09-07 14:30发布

问题:

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).

回答1:

see this fiddle: http://jsfiddle.net/vt6v6L9u/2/

html:

<form>
    <div data-bind="foreach: retrievedUsers">
        <div>
            <label data-bind="attr:{for:$index}">
                <input type="radio" name="people2" data-bind="attr: {id: $index,value: age}, checked: $root.selected" />
                <span data-bind="text: name"></span>
            </label>
        </div>
    </div>
</form>
<div>
    The selected person will be
    <span data-bind="text: SelectedPersonAgeNextYear"></span>
    years old in the upcoming year.
</div>
<button data-bind="click: getUsers">get users</button>

javascript:

var ViewModel = function () {

    var self = this;
    // an array of retrieved user objects
    self.retrievedUsers = ko.observable([]);

    self.getUsers = function () {
        self.retrievedUsers([{ 'name': 'Johnny', 'age': 20 }, { 'name': 'Jenny', 'age': 21 }]);
    };

    self.selected = ko.observable();
    self.SelectedPersonAgeNextYear = ko.computed(function () {
        return parseInt(self.selected(), 10) + 1;
    });
};

ko.applyBindings(new ViewModel());