Search code examples
backbone.js

Backbone.js Work with server response to save() method


I'm kind of new to Backbone. I need use the data in the server response to a save() method but I'm not sure how to get it. This is the code:

$(".act_btn").on("click", function(){
    var act_id = $(this).attr("data-id");
    startRecordItem = new StartRecordItem({
        activity: act_id,
    });
    startRecordItem.save({ 
        success: function(response){console.log(response)}
        });

    /*
    recordItem = new RecordItem({
        id: ... <---- I have to populate this with the data from the server response.
    });
   */

Right now the success function doesn't work at all, what am I missing? I'd like to get an attribute from the JSON response and then use it on the ´new RecordItem´. The save itself works correctly and the response looks like this:

{"activity": 1, "id": 14}

Solution

  • What you're missing is that the first argument of .save. is the attributes that get passed into the model, pre-save. You want to do something more like this:

    startRecordItem.save(null, {
      success: function(response) { 
        console.log(response); 
      }
    });
    

    Since Backbone fires a sync event on successful save, you could also do this:

    this.listenTo(startRecordItem, 'sync', function() { /* logic here */ });