A191919
A191919

Reputation: 3462

Knockout list with jquery event

Why event does not occur on items when I am changing their values?

$(".target").change(function () {
  alert($(".target").val());
});

function MyViewModel() {
  var self = this;
  self.items = ko.observableArray();
  self.items.push({ name: 'Jhon' });
  self.items.push({ name: 'Smith' });
}

ko.applyBindings(new MyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<h2>Index</h2>

<table>
  <thead>
    <tr>
      <th>Passenger name</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: items">
    <tr>
      <td><input class="target" data-bind="value: name" /></td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Views: 39

Answers (1)

jmvtrinidad
jmvtrinidad

Reputation: 3668

Knockout generates new html upon applying foreach bindings, so you need to register your event globally, just like option 1 or you can do the neet binding of knockout just like in option 2. I recommend option 2 to use knockout bindings.

$(document).on('change',".target",function () {
  alert('option 1 - ' + $(this).val());
});

function MyViewModel() {
    var self = this;
    self.items = ko.observableArray();
    self.items.push({ name: 'Jhon' });
    self.items.push({ name: 'Smith' });
    self.alert = function(data, e){
    alert('option 2 - ' + data.name);
  };
}

ko.applyBindings(new MyViewModel(), document.getElementById('tblSample'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<h2>Index</h2>

<table id="tblSample">
  <thead>
    <tr>
      <th>Passenger name</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: items">
    <tr>
      <td><input class="target" data-bind="value: name, event:{change:$parent.alert}" /></td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions