Paweł Reszka
Paweł Reszka

Reputation: 1557

Knockout.js - passing parameters

I have a problem with Knockout.js. I want to pass username to a function and display it on alert. Something strange is happening. I get alerts each time when i refresh page with correct usernames, but after i click it i don't get any response. What is wrong here? Here is my code:

<ul data-bind="foreach: contacts">
   <li class="user-box"><span class="user-box-name" data-bind="text: username, click: $root.userClick(username)"></span>
   </li>
</ul>

and

self.userClick = function (x) {
    alert(x);
}

Upvotes: 9

Views: 19267

Answers (2)

Tomalak
Tomalak

Reputation: 338426

Knockout passes the right object to the event handler. Just do it like this:

<ul data-bind="foreach: contacts">
   <li class="user-box">
     <span 
       class="user-box-name" 
       data-bind="text: username, click: $root.userClick"
     ></span>
   </li>
</ul>

and

self.userClick: function (obj, event) {
    alert(obj.username);
}

Upvotes: 11

Jeff Mercado
Jeff Mercado

Reputation: 134621

The click binding accepts a callback function to be called when the control is clicked.

However in your example, you are calling the function instead. So what happens is every time the page is loaded, the bindings are loaded and your function is invoked as it is written. You need to wrap that in a function so it doesn't get called like that.

<span class="user-box-name"
      data-bind="text: username, click: function () { $root.userClick(username); }">
</span>

Upvotes: 29

Related Questions