Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click bind executing automatically in Knockout Foreach

I have included one click binding inside a foreach loop like the following:

    <tbody data-bind="foreach: locationConfigSet">
         <tr>
          <td data-bind="text: address"></td>
          <td><a data-bind="attr: {href: 'http://maps.google.com/maps?z=12&t=m&q=loc:' + latitude + '+' + longitude}" target="_blank" class="btn btn-primary btn-xs">Map</a></td>
          <td data-bind="text: allowance"></td>
          <td><button class="btn btn-danger btn-xs" data-bind="click: $parent.deleteconfig($data)">Delete</button></td>
         </tr>
    </tbody>

But the function deleteconfig is getting executed as soon as the page is loading (without click) in a loop untill its executed for the exact same times as the foreach loop executes.

like image 371
deDishari Avatar asked May 29 '26 22:05

deDishari


1 Answers

indeed, you need to bind the function.

data-bind="click: $parent.deleteconfig($data)"

invokes the function straightforward.

You can instead use:

data-bind="click: $parent.deleteconfig.bind($parent, $data)"

as explained here

See this snippet :

var elementVM = function(id) {
  this.id = ko.observable(id);
}

var parentVM = function() {
  this.list = ko.observableArray([new elementVM(0), new elementVM(1)]);
  this.onclick = function(text) {
    text(text() + 1);
  }
}

ko.applyBindings(new parentVM());
.child {
  width: 50px;
  text-align: center;
  border: 1px solid black;
  background-color: yellow;
  cursor: pointer;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: list">
  <div class="child" data-bind="click: $parent.onclick.bind($parent, $data.id), text: id"></div>
</div>
like image 192
Regis Portalez Avatar answered May 31 '26 11:05

Regis Portalez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!