成功时将动态 ID 传递给 url backbone

Pass dynamic ID to url on success backbone

我在点击时获得了我的 ID,我使用 destroy 在我的数据库中删除它,我的 ID console.log 工作并且 return 值但是我想将这个 ID 传递给 url 像这样:

'delete': 'http://localhost:3000/api/comments/'+ id

错误:ID 未定义,我不能在成功之外传递它。

这是我的代码:

    var PostPrimary = Backbone.Model.extend({
        methodToURL: {
            'read': 'http://localhost:3000/api/comments',
            'create': 'http://localhost:3000/api/comments',
            'update': 'http://localhost:3000/api/comments/:comment_id',
            'delete': 'http://localhost:3000/api/comments/:comment_id'
        },

        sync: function(method, model, options) {
            options = options || {};
            options.url = model.methodToURL[method.toLowerCase()];

            return Backbone.sync.apply(this, arguments);
        },
        idAttribute: "_id",
        defaults: {
            title: '',
            content: ''
        },
        postdata: function() {
            this.save({
                name: this.get('title'),
                content: this.get('content')
            }, {
                success: function(model) {
                    console.log("save");
                }
            });
        },
        deletedata: function() {
            this.destroy({
                success: function(model) {
                    //GET ID
                    id = model.get('idAttribute');
                    console.log(id);
                }
            });
        }
    });

    return PostPrimary;

Backbone 模型自带处理 url 的实现,你的模型中不需要 methodtoURl 属性。

为您的模型指定 urlRoot,id 将被附加 backbone,例如 [urlRoot]/id

你的模型可以简化为

var PostPrimary = Backbone.Model.extend({
        idAttribute: "_id",
        urlRoot: 'api/comments',
        defaults: {
            title: '',
            content: ''
        }
    });

不需要Postdata等属性可以直接说

Model.save() instead postdata, and model.destroy() instead deletedata()

如果您的模型中没有 ID,您可以创建一个闭包。

  deletedata: function() {

    var id=this.get('idAttribute');

            this.destroy({
                success: function(model) {
                    //GET ID                   
                    console.log(id);
                }
            });
        }