我有一个 API,可以通过传递对象 ID 来删除对象列表(API URL:DELETE/item/deleteall?ids=1,2,3)。在主干中,可以通过调用 destroy 方法来删除个体,但是我如何调用上述端点呢?
define(['backbone'], function(Backbone) {
var ItemsDelete = Backbone.Model.extend({
urlRoot: '/item/deleteall'
});
return ItemsDelete;
});
var itemsDelete = new ItemsDelete();
itemsDelete.destroy({...}); //this doesn't call the end point
如果这不可能或不是最好的方法,请提出替代方案。谢谢。
最佳答案
使用 Backbone 模型作为调用自定义端点来删除多个对象的方式实际上没有意义,因为存在管理一个对象的模型。
destroy
method如果模型是新的(还没有 id
属性),则会相应地避免调用端点。
var xhr = false; if (this.isNew()) { // here it skips the API call _.defer(options.success); } else { wrapError(this, options); xhr = this.sync('delete', this, options); }
在集合上创建自己的 destroy
函数可能更有意义。
// An item model
var Item = Backbone.Model.extend({
urlRoot: '/item',
});
// the collection
var ItemCollection = Backbone.Collection.extend({
model: Item,
destroy: function(options) {
options = options || {};
var ids = options.models || this.pluck(this.model.prototype.idAttribute);
// use the existing `sync` to make the ajax call
this.sync('delete', this, _.extend({
url: _.result(this.model.prototype, 'urlRoot') + "/deleteall",
contentType: 'application/json',
data: JSON.stringify(ids),
}, options));
this.remove(ids, options);
}
});
然后,你可以像这样使用它:
var testCollection = new ItemCollection([{ id: 1 }, { id: 2 }, { id: 3 }, ]);
// destroy specific ids
testCollection.destroy({
models: [1, 2, 3]
});
// destroy all models inside the collection
testCollection.destroy();
ID 位于请求正文中,它们不应位于 URL 中,因为 DELETE
http 动词会影响服务器状态。
关于javascript - 没有 ID 的主干调用 DELETE API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39697919/