Search code examples
javascriptbackbone.js

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


I need to use the model id from the COLLECTION.create call to redirect the user to do new page

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

I do not care if the ajax call to the rest api is async or sync (if that matters). I was hoping I could do something like this:

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

SOMECOLLECTION.create(json_attributes,OPTS)

But that does not work. I am using Django-Tastypie as my REST API.


Solution

  • This should work

    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
    

    I created working example here http://jsfiddle.net/6wup7q9e/3/

    Please check your network tab to see what response you have from your REST API, it should have and your json_response and new id attribute which will be used as a model id. In my case it will be something like:

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