有条件地绑定Knockoutjs中的函数

编程入门 行业动态 更新时间:2024-10-27 16:33:07
本文介绍了有条件地绑定Knockoutjs中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 <div data-bind="foreach: passengers"> <a href="#" data-bind='style: { color: isOwner ? "orange" : "darkgreen" }, text: person_username, click: function() { $root.removePassenger($data, $parent); } '>

说我有一个这样的模板.仅当isOwner为true时,才应绑定click函数.有简单/容易的方法来做到这一点吗?我猜想我可以打破完整的jquery模板并完成一些工作,但是我想知道一个更优雅的解决方案.

Say I have a template like this. The click function should only be bound if isOwner is true. Is there a simple/easy way to do this? I'm guessing I could break out the full jquery templating and get something done, but I'd like to know a more elegant solution.

谢谢.

推荐答案

您要的-仅在设置了某些属性时才处理click事件-是应用程序逻辑.应用程序逻辑不属于该视图.它属于视图模型.

What you're asking for -- handle a click event only when some property is set -- is application logic. Application logic does not belong in the view. It belongs in the view model.

当然,您可以做类似的事情:

Sure, you could do something like:

click: function() { if ($data.isOwner) $root.removePassenger($data, $parent); }

但是,这又一次将逻辑放在您的视图中,从关注点分离和调试的角度来看,这是令人讨厌的,它使您的HTML丑陋了.

But, again, that's putting logic in your view, which is frowned upon from a separation-of-concerns and debugging point of view, and it uglifies your HTML.

我建议这样做:

<div data-bind="foreach: passengers"> <a href="#" data-bind='style: { color: isOwner ? "orange" : "darkgreen" }, text: person_username, click: function() { $root.removePassengerIfApplicable($data, $parent);"</a> </div>

还有您的JavaScript:

And your JavaScript:

function removePassengerIfApplicable(passenger, parent) { if (passenger.isOwner) { removePassenger(passenger, parent); } }

更新

UPDATE

从您的帖子中还不清楚,如果isOwner = false,则您不想显示链接.这是为您提供的一些更新代码:

It wasn't clear from your post that you didn't want to show a link if isOwner = false. Here's some updated code for you:

<div data-bind="foreach: passengers"> <div data-bind="if: isOwner"> <a href="#" style="color: orange" text: person_username, click: function() { $root.removePassenger($data, $parent); }"</a> </div> <div data-bind="if !isOwner()"> <span style="color: darkgreen" data-bind="text: person_username"></span> </div> </div>

上面的代码显示的是isOwner链接,否则为纯文本跨度.

The above code shows a link if isOwner, and a plain text span if not.

更多推荐

有条件地绑定Knockoutjs中的函数

本文发布于:2023-07-26 11:40:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1215999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   绑定   函数   Knockoutjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!