在Ember deleteRecord中添加有效负载

时间:2016-03-05 21:14:23

标签: ember.js ember-data

我需要在尝试删除项目时在用户名中包含用户的备注。到目前为止,我有这个:

let remarks = this.get('remarks');
let id = this.get('itemID');

this.store.findRecord('item', id).then(function (selectedItem) {

    // TODO - DELETE doesn't accept payload in body?

    selectedItem.destroyRecord({remarks:remarks}).then(function(response){

        Ember.debug('delete successful:'+JSON.stringify(response));

        Ember.$('#confirmDelete').modal('hide');
        Ember.$('#remarks').val('');

        context.set('successful', true);
        context.set('message', context.get('i18n').t('success.role.delete'));                        

    }).catch(function(error){
        Ember.debug('delete failed:'+JSON.stringify(error));

        Ember.$('#confirmDelete').modal('hide');
        Ember.$('#remarks').val('');

        context.send('showErrors', error);
    });
});                 

它不起作用。因此,在模型中设置备注值如:

...
this.store.findRecord('item', id).then(function (selectedItem) {

    selectedItem.set('remarks', remarks);

    selectedItem.destroyRecord().then(function(response){
...

我试图覆盖deleteRecord,但我不知道从哪里开始或如何做。

有人有想法吗?谢谢!

1 个答案:

答案 0 :(得分:6)

通过使用以下mixin扩展应用程序适配器,您可以轻松实现此类行为:

/* app/mixins/delete-with-playload.js */

import Ember from 'ember';

export default Ember.Mixin.create({
  deleteRecord(store, type, snapshot) {
    var id = snapshot.id;
    var data = {};
    var serializer = store.serializerFor(type.modelName);

    serializer.serializeIntoHash(data, type, snapshot);

    return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE", {
      data
    });
  }
});

然后将其添加到您的应用程序适配器

/* app/adapters/application.js */

import RestAdapter from 'ember-data/adapters/rest';
import DeleteWithPayloadMixin from '../mixins/delete-with-payload';
export default RestAdapter.extend(DeleteWithPayloadMixin);

这将导致有效负载与PUT方法的有效负载相同,这意味着形式的有效负载:

{
  "<model-name>": {
    // model's serialized attributes
  }
}

现在你所要做的就是在删除之前在记录上设置所需的属性,并销毁记录。

model.setProperties({
  deleteReason: 'whatever'
});
model.destroyRecord();
/* 
results a DELETE request when requestBody is "{
  "<model-name>": { 
    ... 
    "deleteReason": "whatever"
    ...
  }
}"
*/