Push the values of input button in an observable a

2019-09-02 12:50发布

问题:

I am trying to complete a task where I choose the values of buttons and then using two way data binding I print them. My starting code is:

<table class="table">
    <tr>
        <td><input type="button" value="1" data-bind="click: addNumber"></td>
        <td><input type="button" value="2" data-bind="click: addNumber"</td>
        <td><input type="button" value="3" data-bind="click: addNumber"></td>
        <td><input type="button" value="4" data-bind="click: addNumber"></td>
        <td><input type="button" value="5" data-bind="click: addNumber"></td>
        <td><input type="button" value="6" data-bind="click: addNumber"></td>
        <td><input type="button" value="7" data-bind="click: addNumber"></td>
        <td><input type="button" value="8" data-bind="click: addNumber"></td>
        <td><input type="button" value="9" data-bind="click: addNumber"></td>
        <td><input type="button" value="10" data-bind="click: addNumber"></td>
    </tr>
</table>

and my view model is:

function viewModel(){
        var self = this;

        self.column = ko.observableArray();

        self.addNumber = function() {
            self.column.push(...);
            console.log(self.column());
        }  
    }

ko.applyBindings(new viewModel());

I don't know how to write the addNumber function to do the task which is when I click on a button its value gets pushed in the column array.

回答1:

A function for a click bindin will get the contextual data as arguments. It looks like you're rendering a list of numbers anyways, so you should probably use foreach too. Something like this:

function viewModel(){
  var self = this;
  
  self.nrs = ko.observableArray([1,2,3,4,5,6,7,8,9,10]);

  self.column = ko.observableArray();

  self.addNumber = function(data) {
    self.column.push(data);
    console.log(self.column());
  }  
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Column: <strong data-bind="text: column"></strong>.

<table class="table">
  <tbody data-bind="foreach: nrs">
    <tr>
      <td><input type="button" data-bind="value: $data, click: $parent.addNumber"></td>
    </tr>
  </tbody>
</table>

If you want to stick closer to your original code that's possible too. Then you have to tell knockout what argument to pass, using an anonymous function, e.g.:

<td>
  <input type="button" value="1" data-bind="click: function() { addNumber(1); }">
</td>