Ember.js {{each}} vs {{collection}}



我知道eachcollection辅助方法是迭代我的手把模板中的项目列表的两种可能方法。我正在寻找一些关于何时使用eachcollection以及这两种方法之间的区别的实用建议。

每个:

App.myArray = [1,2,3]
{{#each value in App.myArray}}
<p>{{value}}</p>
{{/each}}

相应的HTML

<p>1</p>
<p>2</p>
<p>3</p>

收藏:

{{#collection contentBinding="App.myArray"}}
<p>{{view.content}}</p>
{{/collection}}

相应的HTML

<div class="ember-view">
<p>1</p>
</div>
<div class="ember-view">
<p>2</p>
</div>
<div class="ember-view">
<p>3</p>
</div>

正如您所看到的,两者都处理数组。简而言之,each用于显示元素阵列,而collection用于显示视图阵列

实际使用中的主要区别在于您希望与元素进行交互。如果您只想显示数组的列表,请使用each辅助对象。

但是,如果您想与数组中的每个元素交互,同时维护单击的元素的上下文,则collections

让我以为例进行解释

App.CollectionView = Ember.CollectionView.extend({
//Here the content belongs to collection view
content: [1,2,3],
itemViewClass: Ember.View.extend({
/*This itemViewClass is like a template which is used by 
all the elements in the content array of collection view*/
click: function(){
//Now this itemViewClass has a content property which is the single element in the collections content
/* As you see the content of collection view has 3 elements => 3 templates 
1 single template = Ember.View.extend with it's own content property
first template has content set to 1
second template has content set to 2 and so on...
*/
alert("you clicked"+this.get('content');
}
})
})

我想这消除了你的疑虑。。。

我是Ember.js的新手,还没有使用过{{collection}},但凭借我所掌握的知识和对{(http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_collection),我推测如下:

{{each}}帮助程序将遍历对象列表,并输出针对每个对象呈现的{{each}}标记之间的内容。它只是模板中的一个循环。

{{collection}}帮助程序也会遍历对象列表,但在每次迭代中,它都会创建一个新的View对象来包含它。如果您使用块形式({{#collection}}}}{{/collection}),标记之间的内容将成为和新创建的视图关联的模板。如果您使用单标记形式({{collection}}),而不是直接提供模板,您可以指定要使用的视图的名称,Ember将创建该类的视图(而不是通用的Ember.View)并使用它的关联模板。

使用{{collection}}而不是{{each}}的原因更为复杂和微妙,而且这似乎是你在使用真正的应用程序时遇到它们才真正开始得到的东西——至少,到目前为止,这是我对Ember的许多部分的体验。例如,您会突然意识到,出于某种原因,您需要将循环模板部分作为一个不同的视图对象——可能是为了在某个地方包含额外的事件处理程序,或者存储特定于每个循环迭代的额外UI状态,如isEditing标志。

正如@Abdull在对您的问题的评论中所说,{{collection}}视图助手已被弃用,因此建议使用{{each}}

/**
`{{collection}}` is a `Ember.Handlebars` helper for adding instances of
`Ember.CollectionView` to a template. See `Ember.CollectionView` for
additional information on how a `CollectionView` functions.
...
@method collection
@for Ember.Handlebars.helpers
@param {String} path
@param {Hash} options
@return {String} HTML string
@deprecated Use `{{each}}` helper instead.
*/

源代码:ember.js/packages/ember-handlebars/lib/helpers/collection.js

最新更新