Knockout.js - 传递参数 [英] Knockout.js - passing parameters

查看:106
本文介绍了Knockout.js - 传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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


推荐答案

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

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>

这篇关于Knockout.js - 传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆