使用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動詞會影響服務器狀態。
![ids in the body of the request](https://i.stack.imgur.com/YO5xK.png)