I understand each
and collection
helper methods are two possible ways to iterate over a list of items in my handlebars templates. I am looking for some practical advice about when to use each
or collection
and what are the differences between the two methods.
Each:
App.myArray = [1,2,3]
{{#each value in App.myArray}}
<p>{{value}}</p>
{{/each}}
corresponding HTML
<p>1</p>
<p>2</p>
<p>3</p>
Collection:
{{#collection contentBinding="App.myArray"}}
<p>{{view.content}}</p>
{{/collection}}
corresponding 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>
As you can see both deal with arrays. In a nutshell each
is used to display an array of elements while collection
is used to display an array of views
The main difference comes in practical use is when you want to interact with elements. If you just want to display a list of array use each
helper.
But if you want to interact with each of the element in the array while maintaining context of the clicked element you collections
Let me explain with an example
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');
}
})
})
I think this clears your doubt...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With