javascript Knockout.js - 传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14180876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:56:16  来源:igfitidea点击:

Knockout.js - passing parameters

javascriptknockout.js

提问by Pawe? Reszka

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:

我对 Knockout.js 有问题。我想将用户名传递给一个函数并在警报时显示它。一些奇怪的事情正在发生。每次使用正确的用户名刷新页面时,我都会收到警报,但单击它后,我没有收到任何响应。这里有什么问题?这是我的代码:

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

回答by Jeff Mercado

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

click绑定接受在单击控件时调用的回调函数。

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>

回答by Tomalak

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

Knockout 将正确的对象传递给事件处理程序。只是这样做:

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