有条件地绑定Knockoutjs中的函数 [英] Conditionally bind a function in Knockoutjs

查看:78
本文介绍了有条件地绑定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中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆