Passing a constant or parameter to the data-bind click function in KO.js

1k Views Asked by At

I want to implement a menu. Each button in menu should set the menu ID in the model. I tried to do it this way, but it doesn't work:

<a class="btn btn-primary btn-large"
     data-bind="click:selectUi('menu'),visible:sessionId()!=''">
  Menu
</a>

Instead the selectUi is called when the page loads.

The only possible solution which comes right now to my mind is to implement one function for each button. Is that the right way?

3

There are 3 best solutions below

0
On BEST ANSWER

Wrap your function call in a function.

<a class="btn btn-primary btn-large"
     data-bind="click:function () { selectUi('menu'); },visible:sessionId()!=''">
  Menu
</a>

You could also make selectUi return a function.

0
On

Just for mentioning one possible solution, which I've used before applying the answer of Roy J.

Use the functions without parameters.

e.g:

<a data-bind="click:selectUi_menu"> Menu </a>
1
On

Using the Punches plugin, this is easy:

<a class="btn btn-primary btn-large"
     data-bind="on.click: selectUi('menu'), visible: sessionId()!=''">Menu</a>

Without the plugin, you could use an anonymous function or bind:

<a class="btn btn-primary btn-large"
     data-bind="click: selectUi.bind($data, 'menu'), visible: sessionId()!=''">Menu</a>