Emberjs -同时使用CollectionView和ItemController

Emberjs - Using CollectionView and ItemController together

本文关键字:CollectionView ItemController Emberjs      更新时间:2023-09-26

我有一个模型Category,有许多Documents。当渲染单个Category时,我想在拖放可排序列表中列出所有子documents。我还想双击任何单独的document,以允许内联编辑该文档。

我让两个部分各自工作,但似乎不知道如何将它们合并在一起。

对于可排序的列表,我使用CollectionView的自定义子类来呈现documents,并在插入元素后调用html5sortable jquery插件。

对于内联编辑,我为每个呈现的document设置了一个itemController。在DocumentController中,我保持了编辑文档的应用程序状态。

我正在寻找如何结合这两种方法的见解。我认为我需要的是一种在CollectionView中为每个itemView设置itemController的方法。我把相关的代码放在下面。

App.SortableView = Ember.CollectionView.extend({
    tagName: 'ul',
    itemViewClass: 'App.SortableItemView', 
    didInsertElement: function(){
        var view = this;
        Ember.run.next(function() {
        $(view.get('element')).sortable();
        });
    }
});
App.SortableItemView = Ember.View.extend({
    templateName: 'sortable-item',
    doubleClick: function() {
        //This should ideally send 'editDocument' to controller
    }
});
App.DocumentController = Ember.ObjectController.extend({
    isEditing:false,
    editDocument: function () {
        this.set('isEditing', true);
    },
    finishedEditing: function() {
        var model = this.get('model');
        model.get('store').commit();
        this.set('isEditing', false);
    }
});
<script type="text/x-handlebars" data-template-name="category">
    <h1>{{ name }}</h1>
    <h2>Documents</h2>
    <!-- This makes a sortable list -->
    {{view App.SortableView contentBinding="documents"}}
    <!-- This makes an editable list -->
    {{#each documents itemController="document"}}
        <!-- change markup dependent on isEditing being true or false -->
    {{/each}}
    <!-- How do I combine the two -->
</script> 

谢谢你的帮助。非常感谢。

秘诀是在您的ArrayController上设置itemController,而不是试图在视图上设置它。然后,任何绑定到该ArrayController的视图都将获得一个控制器,而不是它后面的任何内容。

要做到这一点,你必须明确DocumentsController:

App.DocumentsController = Ember.ArrayController.extend({
    needs: ['category'],
    contentBinding: 'controllers.category.documents',
    itemController: 'document'
});

,然后在你的分类中:

App.CategoryController = Ember.ObjectController.extend({
    needs: ['documents']

现在,在你的模板中,绑定到controllers.documents而不是documents

我认为这是Ember的一个bug,即将被解决:

https://github.com/emberjs/ember.js/issues/4137