2016-09-26 3 views
2

개체 ID (API URL : DELETE/item/deleteall? ids = 1,2,3)를 전달하여 개체 목록을 삭제하는 API가 있습니다. 백본을 삭제하는 방법은 destroy 메서드를 호출하여 가능하지만 위의 끝점은 어떻게 호출 할 수 있습니까?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

한 개체를 관리하기위한 모델이 있으므로 여러 끝점 개체를 삭제하기 위해 사용자 지정 끝점을 호출하는 방법으로 백본 모델을 사용하는 것은 실제로 의미가 없습니다.

따라서 모델이 새 (id 속성은 아직 없음) 인 경우 엔드 포인트를 호출하지 않도록 destroy method이 작성됩니다.

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); 
    } 
}); 

그런 다음,이처럼 사용할 수 있습니다 다음 DELETE HTTP 동사가 서버 상태에 영향을 미치는 같이 ID가 요청의 본문에

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(); 

을, 그들은 URL에 안 .

ids in the body of the request