javascript - 没有 ID 的主干调用 DELETE API

标签 javascript backbone.js marionette

我有一个 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 动词会影响服务器状态。

ids in the body of the request

关于javascript - 没有 ID 的主干调用 DELETE API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39697919/

相关文章:

javascript - 在 WebKit 中测量回流和绘制时间

php - 检索访客的书签

javascript - 主干的客户端持久层?

javascript - 将非输入元素与 Backbone.Syphon 一起使用

javascript - 在 javascript 中处理 Canvas 的 OnClick 事件并获取其坐标

javascript - 如何测量 react 虚拟化列表中的行高

javascript - 未捕获的语法错误 : Failed to execute 'querySelector' on 'Document'

javascript - 在 Backbone.sync 中为另一台服务器上的 API 添加绝对 URL 路径

javascript - 如何覆盖 CompositeView 渲染方法?

javascript - 在 marionette 项目中包含 javascript 文件