Success and error callbacks in model.save() are random/asynchronous
I know there are many questions already present on this topic, but none of
the answers have worked for me yet. Please be a bit patient and have a
look at my scenario.
I'm saving my backbone model using backbone's model.save() function on
click event of a Save button.
My objective is to perform certain operation based on the response
returned once the model is saved successfully, like so:
SaveActivity: function( e )
{
this.model.set({'value': 0});
this.model.save(null,
{
success: function (model, response)
{
var id = null;
var stringed = JSON.stringify(model);
/* perform operation with stringed */
}
error: function (model, response)
{
//i am in error
}
}
});
alert("Done"); //This is the alert I am talking about, below
}
I see a very weird behavior of the callback functions in this code. If I
remove alert, then the error callback is fired (always). On the other
hand, with this alert, what happens is - as soon as the button is clicked,
"POST" request is fired for the model to be saved save and then the alert
is popped, irrespective of the fact that "save" is to be completed.
Now comes the catch - If I select "OK" on the alert box, before I have
received a "200 OK" response for the post request (verified through
console again), then the error callback is fired. If I wait for "200 OK"
to come for POST before selecting the alert box, then success callback is
fired. But the problem is, the model is getting saved in both the cases -
whether I wait for 200 OK to come for POST or not. Also, the POST request
takes a few seconds in returning the success response.
I realize that this is because of the asynchronous behavior of the save()
function. But I have tried many things still problem persists. Any help in
this would be really appreciated.
Thanks!!!
No comments:
Post a Comment