javascript 在knockoutjs中评论foreach绑定与foreach绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17068094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:59:14  来源:igfitidea点击:

comment foreach binding vs foreach binding in knockoutjs

javascriptknockout.jstemplatingknockout-templating

提问by Elisabeth

In my HTML I can define these knockout foreach bindings:

在我的 HTML 中,我可以定义这些淘汰赛 foreach 绑定:

<!-- ko foreach: customer -->
   <div data-bind="text: id" />
<!-- /ko -->

vs

对比

<div data-bind="foreach: customer">
    <div data-bind="text: id" />
</div>

Where are the differences between those two approaches?

这两种方法的区别在哪里?

回答by David East

Use native binding when a parent-child relationship exists within the binding section, like a ul and a li.

当绑定部分中存在父子关系时,使用原生绑定,例如 ul 和 li。

Use the comment syntax for containerless binding when your binding section does not have a parent-child relationship.

当您的绑定部分没有父子关系时,使用无容器绑定的注释语法。

In your example you use the first code block because you are not trying to bind to a parent-child structure. All you want to do is just bind your customer data to a div, you shouldn't have to create a parent div and foreachthrough the customers and append another div inside of the parent div. It's more than you want to do.

在您的示例中,您使用第一个代码块,因为您没有尝试绑定到父子结构。您要做的只是将您的客户数据绑定到一个 div,您不必创建父 div 并foreach通过客户并在父 div 内附加另一个 div。这比你想做的要多。

Good use of containerless binding

善用无容器绑定

<!-- ko foreach: customer -->
<section>
   <p data-bind="text: customer.name"></p>
   <p data-bind="text: customer.orderDate"></p>
</section>
<!-- /ko -->

However, if you have an ordered listyou should use the native bindingbecause it just makes sense.

但是,如果您有一个有序列表,您应该使用本机绑定,因为它很有意义。

Native

本国的

<ol data-bind="foreach: customer">
   <li data-bind="text: customer.name"></li>
</ol>

Containerless

无容器

<ol> 
   <!-- ko foreach: customer -->
       <li data-bind="text: customer.name"></li>
   <!-- /ko -->
</ol>

The second example just looks silly. You're adding more complexity for something that shouldn't be complicated.

第二个例子看起来很傻。你为不应该复杂的事情增加了更多的复杂性。

回答by Claudio Redi

In some cases, you might want to duplicate a section of markup, but you don't have any container element on which to put a foreach binding

在某些情况下,您可能想要复制一部分标记,但您没有任何容器元素可以放置 foreach 绑定

To handle this, you can use the containerless control flow syntax, which is based on comment tags

为了解决这个问题,您可以使用基于注释标签的无容器控制流语法

Mode details on The "foreach" binding, Note 4: Using foreach without a container element

“foreach”绑定的模式详细信息,注 4:在没有容器元素的情况下使用 foreach