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);
}
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 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With