将动态ID传递到成功主干上的url

Pass dynamic ID to url on success backbone

本文关键字:url 成功 动态 ID      更新时间:2024-03-25

我在点击时获得我的id,我使用destroy在我的数据库中删除它,我的id console.log工作并返回值,但我想在url上传递这个id,如下所示:

'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将由主干(如[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);
                }
            });
        }