KnockOutJs: Why does click data-bind has execute on-load of element?

前端 未结 3 1975
一生所求
一生所求 2020-12-08 19:52

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

相关标签:
3条回答
  • 2020-12-08 20:40

    from official documentation :

    <button data-bind="click: myFunction.bind($data, 'param1', 'param2')">Click me</button>
    
    0 讨论(0)
  • 2020-12-08 20:48

    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

    0 讨论(0)
  • 2020-12-08 20:49

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

    0 讨论(0)
提交回复
热议问题