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 code generated.
html:
<a data-bind="click: addOrderedProducts(11,"CRM130930001","Cream",0.00,0,0,0)" class="Add" title="Add" href="">Add</a>
ko function:
self.addOrderedProducts = function (id,product_number,name,price,quantity,discount,balance){
self.orderedProducts.push(new Product(id,product_number,name,price,quantity,discount,balance));
};
please help me... Thanks in advance :)
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: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) offunction
objects which returns a new anonymous function that, when invoked, will take its context (i.e. itsthis
value) from the first argument tobind
and its first few arguments from any additional arguments passed tobind
).BTW (although nobody did it here) it's worth mentioning that it's never necessary to write something like:
Instead you can just write
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).
from official documentation :