Knockout.js - passing parameters

2019-04-05 20:27发布

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

2条回答
疯言疯语
2楼-- · 2019-04-05 21:02

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>
查看更多
聊天终结者
3楼-- · 2019-04-05 21:11

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);
}
查看更多
登录 后发表回答