knockout js passing correct parameter to method

2019-08-02 09:17发布

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();
}

2条回答
smile是对你的礼貌
2楼-- · 2019-08-02 09:58

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>
查看更多
一夜七次
3楼-- · 2019-08-02 10:13

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.

查看更多
登录 后发表回答