Ember.js{{each}}vs{{collection}
我知道Ember.js{{each}}vs{{collection},ember.js,Ember.js,我知道每个和集合助手方法是在我的把手模板中迭代项目列表的两种可能的方法。我正在寻找一些关于何时使用每个或集合的实用建议,以及这两种方法之间的区别。我不熟悉Ember.js,我还没有使用过{{collection},但我拥有的知识和{collection}的文档(http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_collection),我推测如下: {{each}}助手将迭代对象列表,并输出针对每个对象呈现的{e
每个
和集合
助手方法是在我的把手模板中迭代项目列表的两种可能的方法。我正在寻找一些关于何时使用每个或集合
的实用建议,以及这两种方法之间的区别。我不熟悉Ember.js,我还没有使用过{{collection},但我拥有的知识和{collection}的文档(http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_collection),我推测如下:
{{each}}助手将迭代对象列表,并输出针对每个对象呈现的{each}}标记之间的内容。它只是模板中的一个循环
{{collection}}助手也将迭代对象列表,但在每次迭代中,它将创建一个新的视图对象来包含它,而不是在那里提供模板,而是指定要使用的视图的名称,Ember将创建该类的视图(而不是泛型Ember.View)并使用其关联的模板
使用{{collection}而不是{{each}的原因更为复杂和微妙,这似乎是你在开发一个真正的应用程序时才开始真正遇到它们的那种东西——至少,这是我到目前为止对Ember的许多部分的体验。例如,你会突然意识到,出于某种原因,你需要你的循环模板部分成为一个独特的视图对象——可能是为了保存到某个地方以包含其他事件处理程序,或存储特定于每个循环迭代的其他UI状态,如isEditing标志。每个:
App.myArray = [1,2,3]
{{#each value in App.myArray}}
<p>{{value}}</p>
{{/each}}
{{#collection contentBinding="App.myArray"}}
<p>{{view.content}}</p>
{{/collection}}
我认为这消除了您的疑虑…正如@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.
*/
源代码:此外,每个助手都会在周围添加标记。因此,如果要使用jQuery选择器或jQuery UI元素,请使用collection helper以确保安全。为了防止
标记绑定,您可以在handlebar属性之前添加unbound
,如:{unbound value}
,使用Ember 1.0.0 RC3(可能更早),已弃用。
<div class="ember-view">
<p>1</p>
</div>
<div class="ember-view">
<p>2</p>
</div>
<div class="ember-view">
<p>3</p>
</div>
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');
}
})
})
/**
`{{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.
*/