knockout js passing correct parameter to method

2019-08-02 09:10发布

问题:

when using the click bind in knockout, how does knockout know to pass the correct parameter to the method its bound to?

<div id="test" data-bind="click: runTest"/>
</div>


self.runTest = function (coolParameter){
doSomethingCool();
}

回答1:

When calling your handler, Knockout will supply the current model value as the first parameter. This is particularly useful if you’re rendering some UI for each item in a collection, and you need to know which item’s UI was clicked.

from the documentation

There also is some discussion in the docs about how to pass more parameters by adding a wrapping function

<button data-bind="click: function(data, event) { 
    myFunction('param1', 'param2', data, event) 
}">
    Click me
</button>


回答2:

knockout understands which value to pass from context. it's the current model object. e.g if you're in a foreach knockout passes the current item.