KnockOutJs: Why does click data-bind has execute o

2019-01-17 11:01发布

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 :)

3条回答
放荡不羁爱自由
2楼-- · 2019-01-17 11:17

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

查看更多
看我几分像从前
3楼-- · 2019-01-17 11:26

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).

查看更多
闹够了就滚
4楼-- · 2019-01-17 11:26

from official documentation :

<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">Click me</button>
查看更多
登录 后发表回答