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

后端 未结 3 691
孤城傲影
孤城傲影 2021-02-19 17:11

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

3条回答
  •  余生分开走
    2021-02-19 17:39

    Each:

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

    {{value}}

    {{/each}}

    corresponding HTML

    1

    2

    3

    Collection:

    {{#collection contentBinding="App.myArray"}}
      

    {{view.content}}

    {{/collection}}

    corresponding HTML

    1

    2

    3

    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...

提交回复
热议问题