[英]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: 我有一个简单的
loggedIn
属性,它是一个作为布尔值的ko
绑定,因此当一个人登录(检查带有异步xhr以确认服务器端的检查)时,应在标头中显示一个元素:
<!-- 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. 上面是从显示/隐藏角度进行的工作,即,如果
loggedIn
为true
则显示“ Log Out
链接。
The problem I'm running into is binding jQuery to the elements, even with .on
: 我
.on
的问题是将jQuery绑定到元素,即使使用.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. 如果刷新页面,它将起作用,但是任何动态更改都使我无法绑定到click(或任何其他)事件。
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. 做到这一点的一种好方法是在您的vm中拥有一个可以完成工作的函数,而不是依赖于jquery事件。 Then bind the click event to your function.
然后将click事件绑定到您的函数。
<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
: 我发现的解决方案是使用
ko
的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. 这似乎完美地工作,允许jQuery毫无问题地绑定元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.