简体   繁体   中英

jQuery Events not binding to knockout conditional elements

I have a simple loggedIn property as a ko binding as a boolean, so when a person is logged in (a check which has an async xhr to confirm server-side) an element in the header should be shown:

<!-- ko if: loggedIn -->
<div class="loggedin">
  <a class="logout">Log Out</a>
</div>
<!-- /ko -->

<!-- ko ifnot: loggedIn -->
<div class="loggedout">
  <a class="login">Log In</a>
  <a class="signup">Signup</a>
</div>
<!-- /ko -->

The above works from a show/hide perspective, ie if loggedIn is true it shows the Log Out link.

The problem I'm running into is binding jQuery to the elements, even with .on :

$('.loggedin').on('click', '.logout', function () {
   // Never fires...
});

It will work if I refresh the page, but any dynamic change leaves me unable to bind to the click (or any other) event.

UPDATE: I've created a fiddle to show the issue

One good way of doing this is to have a function in your vm that does the work instead of relying on jquery events. Then bind the click event to your function.

<div class="loggedout" data-bind="click: someVMFunction">
<a class="login">Log In</a>
<a class="signup">Signup</a>
</div>

The solution I found was to use ko 's visible :

<div class="loggedin" data-bind="visible: loggedIn()">
   <a class="logout">Log Out</a>
</div>

<div class="loggedout" data-bind="visible: !loggedIn()">
   <a class="login">Log In</a>
   <a class="signup">Signup</a>
</div>

Which seems to work perfectly, allowing the elements to be bound to by jQuery without issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM