如何从collection.create调用中获取model.id

How do you get the model.id from the collection.create call?

本文关键字:获取 model id 调用 create collection      更新时间:2023-09-26

我需要使用COLLECTION.create调用中的模型id来重定向用户以执行新页面

window.href = 'https://example.com/document/' + model.id

我不在乎对rest api的ajax调用是异步的还是同步的(如果这很重要的话)。我希望我能做这样的事情:

var OPTS ={}
OPTS['success'] = function( response, model, options ){
                model.id
}
SOMECOLLECTION.create(json_attributes,OPTS)

但这并不奏效。我使用Django-Tastypie作为我的REST API。

这应该能在中工作

var MyCollection = Backbone.Collection.extend({
    url: '/echo/json/'
});
var my_collection = new MyCollection();
var model = my_collection.create({ name: "Eugene", age: 31 }, {
    success: function(response, model) {
        console.log(model.id);
        // id: 123
    }
});
console.log(model.id);
// id: undefined

我在这里创建了工作示例http://jsfiddle.net/6wup7q9e/3/

请检查你的网络选项卡,看看你从你的REST API得到了什么响应,它应该有什么响应,你的json_response和新的id属性将用作模型id。在我的情况下,它将类似于:

{
    id: 123,
    name: "Eugene",
    age: 31
}