Knockout click binding with parameters
Even though you can fix it with a bind
in your click binding, I don't think this is the best solution.
The click
binding passes the clicked model to the listener by default. Bind will create a new function for each item and moves logic to your views.
Here's an example:
var data = [
{ Id: 0, Category: "A", Name: "A0" },
{ Id: 1, Category: "B", Name: "B1" },
{ Id: 2, Category: "C", Name: "C2" },
{ Id: 3, Category: "D", Name: "D3" }
];
ko.applyBindings({
data: data,
log: function(item) {
console.log(item);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: data">
<li data-bind="click: $parent.log, text: Name"></li>
</ul>
Create an extra onClick
function if you need to extract properties to an argument list:
var data = [
{ Id: 0, Category: "A", Name: "A0" },
{ Id: 1, Category: "B", Name: "B1" },
{ Id: 2, Category: "C", Name: "C2" },
{ Id: 3, Category: "D", Name: "D3" }
];
var log = function(id, cat, name) {
console.log("Item ", id, "was clicked. (name:", name, "category:", cat);
}
ko.applyBindings({
data: data,
onClick: function(item) {
log(item.Id, item.Category, item.Name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: data">
<li data-bind="click: $parent.onClick, text: Name"></li>
</ul>
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>