ember.js displaying list of items, each item with it's own view/controller

前端 未结 2 2039
再見小時候
再見小時候 2021-02-10 16:59

What I want to achieve: create controller with view, and in this view I have list of \'Gallery\' objects. Each item has it\'s own view and controller.

All files are her

2条回答
  •  执笔经年
    2021-02-10 17:09

    I think that I maybe should use {{collection}} helper, but there is no documentation for it on ember.js page (there is some in code, but I'm not sure if this helper is not a little bit outdated, as in source it says "// TODO: Don't require all of this module").

    Agreed. Collection helper still works but I'm not certain it will be part of the public-api going forward. Best to stick with the {{#each}} helper if you can.

    I tried to use itemController property, but then I still have template in one file.

    The itemController property is a good start. that's the best way to give each item it's own controller.

    Also tried to use {{render}} helper in {{#each}}, but then it throw error.

    Yeah the {{render}} helper is not designed for use within an {{each}} block.

    So, It is there a better/cleaner way to achieve what I want?

    Yep. For starters use the itemController property. Then to give each it's own view, provide an itemViewClass option to the {{each helper}}. For example:

    # in galleries_index.hbs
    {{each controller itemViewClass="App.GalleriesIndexItemView"}
    

    See the "blockless use" section of api docs for the each helper for detail.

    Then customize App.GalleriesIndexItemView to specify a template:

    App.GalleriesIndexItemView = Ember.View.extend({
        templateName: "galleries_index_item",
        tagName: 'li',
        classNames: ['span4'],
        hover: false,
        mouseEnter: function() {
            this.set('hover', true);
        },
        mouseLeave: function() {
            this.set('hover', false);
        }
    });
    

    and move html from the each helper to into the template:

    # galleries_index_item.hbs
      

    {{name}}

    {{#if view.hover}} {{/if}}

    Now every item has it's own view and controller.

提交回复
热议问题