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

后端 未结 3 693
孤城傲影
孤城傲影 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:26

    I'm new to Ember.js, and I haven't used {{collection}} yet, but with what knowledge I have and a glance at the docs for {{collection}} (http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_collection), I surmise the following:

    The {{each}} helper will iterate over a list of objects and output the contents between the {{each}} tags rendered against each object. It's just a loop within a template.

    The {{collection}} helper will also iterate over a list of objects, but in each iteration it will create a new View object to contain it. If you use the block form ({{#collection}}{{/collection}}), the contents between the tags will become the template associated with the the newly created view. If you use the single-tag form ({{collection}}), instead of supplying the template right there, you specify the name of the View to use, and Ember will create views of that class (rather than generic Ember.View) and use it's associated template.

    The reason to use {{collection}} instead of {{each}} is more complex and subtle, and it seems like the kind of thing you only start to really get from encountering them while working on a real app - at least, that's been my experience so far with many parts of Ember. For example, you'll suddenly realize you need your looped template section to be a distinct view object for some reason - maybe to have somewhere to include additional event handlers, or store additional UI state specific to each loop iteration, like an isEditing flag.

提交回复
热议问题