I have a anchor link generated via php which will be binded on ko and works fine. My problem is why does the ko function is executed on load of the elements? below is the co
from official documentation :
<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">Click me</button>
This is how object literals are working in Javascript so the property values like function class immediately evaluated when the object gets created.
To make it work you need to wrap your function call in the click
binding into an anonymous function:
<a data-bind="click: function () { addOrderedProducts( ... ) }" href="">Add</a>
See also in the documentation: Accessing the event object, or passing more parameters
Alternatively, you could use ...click: addOrderedProducts.bind($data,...)
which I think is slightly cleaner (though it's somewhat a matter of personal taste).
bind
is an ES5 method (Knockout shims it for non-ES5 browsers) of function
objects which returns a new anonymous function that, when invoked, will take its context (i.e. its this
value) from the first argument to bind
and its first few arguments from any additional arguments passed to bind
).
BTW (although nobody did it here) it's worth mentioning that it's never necessary to write something like:
functionWithCallback(..., function(data) {
someOtherFunction(data);
});
Instead you can just write
functionWithCallback(..., someOtherFunction);
A function's name is as much of a function reference as an anonymous function expression; it's not necessary to write the latter in order to get one (of course you do need an anonymous function if the callback involves more code than just a single function call).