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?
KnockoutJS - Click Binding. Click binding is one of the simplest binding and is used to invoke a JavaScript function associated with a DOM element based on a click. This binding works like an event handler. This is most commonly used with elements such as button, input, and a, but actually works with any visible DOM element.
Knockout will pass the event as the second parameter to your function, as in this example: If you need to pass more parameters, one way to do it is by wrapping your handler in a function literal that takes in a parameter, as in this example:
However, the clickBubble binding that we added with a value of false prevents the event from making it past myButtonHandler. Knockout will use jQuery, if it is present, for handling UI events such as click.
Of course, you don’t have to worry about releasing any event handlers created by standard Knockout bindings in your view, as KO automatically unregisters them when the elements are removed. console.log ('Another second passed, and the component is still alive.');
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){
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With