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

Ara*_*ras 12 ember.js

我理解eachcollection辅助方法是迭代我的手柄模板中的项目列表的两种可能方法.我要寻找有关何时使用一些实用的建议eachcollection什么是两种方法之间的差异.

Mud*_*Ali 26

每:

App.myArray = [1,2,3]

{{#each value in App.myArray}}
  <p>{{value}}</p>
{{/each}}
Run Code Online (Sandbox Code Playgroud)

相应的HTML

<p>1</p>
<p>2</p>
<p>3</p>
Run Code Online (Sandbox Code Playgroud)

采集:

{{#collection contentBinding="App.myArray"}}
  <p>{{view.content}}</p>
{{/collection}}
Run Code Online (Sandbox Code Playgroud)

相应的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>
Run Code Online (Sandbox Code Playgroud)

你可以看到两者都处理数组.简而言之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');
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

我认为这清除了你的怀疑......

  • 每个助手也会在<p>周围添加<script>标签.因此,如果您要使用jQuery选择器或jQuery UI元素,请使用集合助手以确保安全. (3认同)

odi*_*ity 5

我是Ember.js的新手,我还没有使用过{{collection}},但是我已经掌握了什么知识并且只看了{{collection}}的文档(http://emberjs.com/api /classes/Ember.Handlebars.helpers.html#method_collection),我推测以下内容:

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

{{collection}}帮助器也将迭代一个对象列表,但在每次迭代中它将创建一个新的View对象来包含它.如果使用块形式({{#collection}} {{/ collection}}),则标记之间的内容将成为与新创建的视图关联的模板.如果您使用单标签表单({{collection}}),而不是在那里提供模板,则指定要使用的View的名称,Ember将创建该类的视图(而不是通用的Ember.View)并使用它的相关模板.

使用{{collection}}而不是{{each}}的原因更为复杂和微妙,而且看起来你在开始真正的应用程序时遇到它们时才开始真正得到的东西 - 至少,那是到目前为止我一直是Ember的许多部分.例如,您会突然意识到由于某种原因,您需要将循环模板部分作为一个独特的视图对象 - 可能包含其他事件处理程序,或者存储特定于每个循环迭代的其他UI状态,如isEditing标志.