Ember是否有可以与{{#collection}}一起使用的{{itemView}}帮助器?

时间:2012-12-21 05:36:30

标签: collections ember.js each

实际上,我正在寻找让View负责标记集合视图中第一个或最后一个项目的方法,我找到了这个How do I add a separator between elements in an {{#each}} loop except after the last element? 。但我不想在javascript中定义itemViewClass模板的attrs(例如classNames),我可以使用{{itemView}}帮助器或其他东西来定义itemView模板吗?

{{#collection contentBinding="dataList" tagName="ol" classNames="list" itemViewClass="ItemView"}}
    {{#itemView classNames="item" classNamesBinding="isLastItem:last"}}
        item templates
    {{/itemView}}
{{/collection}}

虽然这可以用另一种方式解决,但我只想知道我是否能找到内置支持。我搜索了很长时间,但找不到Ember.Handlebars.collection的文档,它不在最新的API文档中。

1 个答案:

答案 0 :(得分:0)

从Emberjs的主版本开始,您可以尝试使用自定义Handlebars“绑定”帮助程序。 它看起来像这样:

{{#each item in collection}}
    {{#isLastElement item}}
        template if last
    {{else}}
        template if not
    {{/isLastElement}}    

    both templates
{{/each}}


Ember.Handlebars.registerBoundHelper('islastElement', 
    function(item, options) {
     if(functionTellingIfThisIsLastElement(item))
          return options.fn(this);
     else
          return options.inverse(this);
    }
);

这只是看待事物的另一种方式, functionTellingIfThisIsLastElement 要么查看集合,要么查看项目中的属性。要访问该集合,您必须在此处更改一些内容,以获取良好的上下文+参数,具体取决于您的代码。

相关问题