add/delete items from Ember Data backed ArrayController

前端 未结 4 756
旧时难觅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条回答
  •  囚心锁ツ
    2021-01-18 02:33

    Foreword

    I had a similar problem and found a little tricky solution. Running through the Ember-Data source code and API docs cleared for me the fact that AdapterPopulatedRecordArray returns from the queried find requests. Thats what manual says:

    AdapterPopulatedRecordArray represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the AdapterPopulatedRecordArray.

    So the good reason for immutability is that this data is controlled by the server. But what if I dont need that? For example I have a Tasklist model with a number of Tasks and I find them in a TasklistController in a way like

    this.get('store').find('task',{tasklist_id: this.get('model').get('id')})
    

    And also I have a big-red-button "Add Task" which must create and save a new record but I dont want to make a new find request to server in order to redraw my template and show the new task. Good practice for me will be something like

    var task = this.store.createRecord('task', {
        id: Utils.generateGUID(),
        name: 'Lorem ipsum'
    });
    this.get('tasks').pushObject(task);
    

    In that case I got announced error. But hey, I want to drink-and-drive!

    Solution

    DS.AdapterPopulatedRecordArray.reopen({
        replace: DS.RecordArray.replace
    })
    

    So that's it. A little "on my own" ember flexibility hack.

提交回复
热议问题