2016-09-26 21 views
2

我有一個API通過傳遞對象ID(API URL:DELETE/item/deleteall?id = 1,2,3)來刪除對象列表。在骨幹刪除個人是可能的通過調用銷燬方法,但我怎麼能稱呼上述終點?Backbone調用不帶ID的DELETE API

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 

如果這是不可能或不是最好的方法,請建議替代方案。謝謝。

回答

3

使用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

相關問題