如何在数据绑定视图中模板 If-Else 结构? [英] How to template If-Else structures in data-bound views?

查看:13
本文介绍了如何在数据绑定视图中模板 If-Else 结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己在基于 KO 的 HTML 模板中使用这个习语:

I constantly find myself using this idiom in KO-based HTML templates:

<!-- ko if: isEdit -->
<td><input type="text" name="email" data-bind="value: email" /></td>
<!-- /ko -->
<!-- ko ifnot: isEdit -->
<td data-bind="text: email"></td>
<!-- /ko -->

在 KO 中是否有更好/更简洁的方法来执行条件语句,或者是否有比仅使用传统的 if-else 结构更好的方法?

Is there a better/cleaner way to do conditionals in KO, or is there a better approach than just using traditional if-else constructs?

另外,我想指出某些版本的 Internet Explorer (IE 8/9) 不能正确解析上述示例.请参阅这个问题了解更多信息.快速总结是,不要在表标签内使用注释(虚拟绑定)来支持 IE.使用 tbody 代替:

Also, I would just like to point out that some versions of Internet Explorer (IE 8/9) don't parse the above example correctly. Please see this SO question for more information. The quick summary is, don't use comments (virtual bindings) inside table tags to support IE. Use the tbody instead:

<tbody data-bind="if: display"><tr><td>hello</td></tr></tbody>

推荐答案

有几种不同的方法可以处理此类代码.

There are a couple different ways that you can handle this type of code.

  • 像你现在这样的 if/ifnot 组合.这工作正常,而且不是非常冗长.

  • with an if/ifnot combination like you are now. This works fine and is not terribly verbose.

Michael Best 的 switch/case 绑定 (https://github.com/mbest/Knockout-switch-case) 非常灵活,可以让您轻松处理这个和更复杂的(比真/假更多的状态).

Michael Best's switch/case binding (https://github.com/mbest/knockout-switch-case) is quite flexible and can let you easily handle this and more complicated ones (more states than true/false).

另一种选择是使用动态模板.您可以将一个区域绑定到一个或多个模板,并使用基于可观察的模板名称.这是我不久前写的关于这个主题的帖子:http://www.knockmeout.net/2011/03/quick-tip-dynamically-changed.html.在您的场景中,它可能如下所示:

Another option is to use dynamic templates. You would bind an area to one or more templates with the template name being used based on an observable. Here is a post that I wrote on this topic a while back: http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html. In your scenario, it might look like:

<td data-bind="template: $root.getCellTemplate"></td>

<script id="cellEditTmpl" type="text/html">
    <input type="text" name="email" data-bind="value: email" />
</script>

<script id="cellTmpl" type="text/html">
    <span data-bind="text: email"></span>
</script>

getCellTemplate 函数可以存在于任何地方,但会被赋予项目 ($data) 作为第一个参数并返回要使用的模板的名称.

The getCellTemplate function could live wherever, but would be given the item ($data) as the first argument and would return the name of the template to use.

这篇关于如何在数据绑定视图中模板 If-Else 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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