Dana Dana - 1 month ago 22
Javascript Question

Knockout click binding with parameters

I'm trying to add an click event to my button that will send the Id, Category and Name as parameters only when the button is clicked.

<tbody data-bind="foreach: tehTab()">
<tr>
<td data-bind="text: $data.Category"></td>
<td data-bind="text: $data.Name"></td>
<td>
<button type="button" class="btn chart_btn" role="button" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="right" container="body" tabindex="0" data-original-title="" title="" style="border:none; background-color:white" data-bind="attr: { id: $data.Id,'data-contentwrapper':'.chartdraw' + $data.Id},click: getLast7($data.Id, $data.Category, $data.Name) , text:$data.Value"></button>
<div data-bind="css: 'chartdraw' + $data.Id" class="chartdrawetc" style="display:none">ASD</div>
</td>
</tr>
</tbody>


even if I try to change:

click: getLast7($data.Id, $data.Category, $data.Name)


with

attr: { id: $data.Id ,onclick: getLast7($data.Id, $data.Category, $data.Name)


it still fires the getLast7 method as many times as the tehTab length.

What am I doing wrong?

Answer

Adding () after function name will call it. You will have to use .bind

click: getLast7.bind(this, $data.Id, $data.Category, $data.Name)

Sample

function vm(){
  this.notify = function(str){
    console.log(str)
  }
}

ko.applyBindings(new vm())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<div data-bind="click: notify.bind(this, 'Hello')">Click me</div>