Dana Dana - 1 year ago 185
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()">
<td data-bind="text: $data.Category"></td>
<td data-bind="text: $data.Name"></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>

even if I try to change:

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


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 Source

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

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


function vm(){
  this.notify = function(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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download