Reputation: 1984
I'm confused on how the parameters are passed into the function from the HTML.
<tbody data-bind="foreach: colorItem">
<tr>
<td data-bind="click: $root.colorTest.bind($data, 'red', 'blue'), text: 'color'"></td>
</tr>
</tbody>
public colorTest(data, param1, param2) {
if (param1 == 'red'){
// do something
}
In the colorTest function, I expect 'data' to hold $data and 'param1' to hold the value 'red' and 'param2' to hold the value 'blue'.
However, $data always gets passed into the last parameter field. So in the colorTest function, data = 'red', param1 = 'blue', param2 = '$data'.
Is this how knockout works? $data is always passed into a function as the last parameter even if it is placed first in the HTML data-bind?
Upvotes: 2
Views: 2181
Reputation: 3192
Have the function in your viewmodel return a function.
ko.applyBindings({
colorTest: function(param1, param2) {
return function() {
console.log('param1 is ' + param1 + ' and param2 is ' + param2);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button data-bind="click: colorTest('red', 'blue')">Color (click me!)</button>
Upvotes: 0
Reputation: 4304
The .bind function isn't a part of knockout it's a javascript function, and the first parameter is always supposed to be the "this" context. So only the parameters after the first one get passed in as arguments. Reference
You should modify your binding as follows:
click: $root.colorTest.bind($root, $data, 'red', 'blue')
Knockout calls the function with $data and $event, which get passed after the bound arguments.
Upvotes: 3