Reputation: 1387
Lets talk with code:
<div class="alert alert-info" role="alert" title="Shows player rankings">
<ul class="nav nav-pills" data-bind="foreach: userRanks">
<!-- ko if: ($index() === 0) -->
<li>
<a href="#" class="btn btn-default" title="Refresh ranks"><i class="glyphicon glyphicon-refresh"></i></a>
</li>
<!-- /ko -->
<li>
<a href="#" data-bind="attr: { title: $data.rank}">
<!-- ko text: $data.username --><!-- /ko -->
<span class="badge" data-bind="text: $data.score"></span>
</a>
</li>
<!-- ko if: ($index() === ($parent.userRanks().length - 1)) -->
<li class="pull-right">
<a href="javascript:void(0)" id="btnPush" class="btn btn-default" data-url="@Url.Action("PushPlayerinfo", "Home")">Update score</a>
</li>
<li class="pull-right" data-bind="attr: {title: $parent.currentUserName}">
<a href="#">You <span class="badge" data-bind="text: $parent.currentUsertotalScore"></span> / <span data-bind="text: $parent.currentUserRank"></span></a>
</li>
<!-- /ko -->
</ul>
</div>
I have registered click handler to link 'btnPush' as:
$("#btnPush").on('click', function () {
//My code
});
Just using knockout foreach control, virtual elements and contexts, don't know what i am missing but click never get registered for this link this way. Inline Html onClick()
works though:
<a href="javascript:void(0)" onclick="pushData(this);" id="btnPush" class="btn btn-default" title="Click to persist current score" data-url="@Url.Action("PushPlayerinfo", "Home")">Update score</a>
Also, if same link is outside of ul-container (Outside of foreach binding), it works fine. Can someone suggest me please?
Upvotes: 0
Views: 2185
Reputation: 4243
You should handle the click event with knockout. It is a bad practice use jQuery to handle the DOM when you use knockout and also it will easy if you use the ko click binding.
Check the documentation: http://knockoutjs.com/documentation/click-binding.html
*If you need run a method inside a ko foreach, and this method belongs to the VM remember to use the $parent or $root key.
<ul data-bind="foreach: items">
<li>
<a data-bind="click: $parent.yourMethod()>link</a>
</li>
</ul>
Upvotes: 1