Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 206
Paweł Reszka Avatar asked Jan 06 '13 09:01

Paweł Reszka


2 Answers

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>
like image 114
Jeff Mercado Avatar answered Sep 28 '22 23:09

Jeff Mercado


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);
}
like image 39
Tomalak Avatar answered Sep 28 '22 22:09

Tomalak