add/delete items from Ember Data backed ArrayController

前端 未结 4 784
旧时难觅i
旧时难觅i 2021-01-18 01:59

I\'m using an ArrayController in my application that is fed from a Ember Data REST call via the application\'s Router:

postsController.connectOutlet(\'commen         


        
4条回答
  •  Happy的楠姐
    2021-01-18 02:45

    Here is what I ended up implementing to solve this. As proposed in the question, the only solution I know about is to create a mutable copy of the content that I maintain through add and deletes:

    contentChanged: function() {
        var mutableComments = [];
    
        this.get('content').forEach(function(comment) {
            mutableComments.pushObject(comment);
        });
    
        this.set('currentComments', mutableComments);
    }.observes('content', 'content.isLoaded'),
    
    addComment: function(comment) {
        var i;
        var currentComments = this.get('currentComments');
        for (i = 0; i < this.get('currentComments.length'); i++) {
            if (currentComments[i].get('date') < comment.get('date')) {
                this.get('currentComments').insertAt(i, comment);
                return;
            }
        }
    
        // fell through --> add it to the end.
        this.get('currentComments').pushObject(comment);
    },
    
    removeComment: function(comment) {
        this.get('currentComments').forEach(function(item, i, currentComments) {
            if (item.get('id') == comment.get('id')) {
                currentComments.removeAt(i, 1);
            }
        });
    }
    

    Then in the template, bind to the this computed property:

    {{#each comment in currentComments}}
        ...
    {{/each}}
    

    I'm not satisfied with this solution - if there is a better way to do it, I'd love to hear about it.

提交回复
热议问题