Reputation: 31
Can somebody explain to me the ascending order of the alerts, and the item values of the model in the following piece of backbone.js code?
var model = new Ingredient({"item" : "Before",});
alert("1");
alert(model.get('item')); // Before
model.fetch({ success: function() {
alert("3");
alert(model.get('item')); // After
}});
alert("2");
alert(model.get('item')); // Before
I can't seem to figure out how to update the state of the model in the same scope which it was defined. Is that important?
It's possible I'm thinking about this the wrong way, or I don't understand something fundamental about javascript scoping or functions.
Thanks
Upvotes: 1
Views: 464
Reputation: 32182
The success: function() is called asynchronously as it is really just a wrapper around a JQuery AJAX call. In human speak -. The fetch method makes a request to the server for the model data. The fetch method returns immediately and doesn't wait for the http request to complete. When the http request completes ( if successfully ) then the success: function() callback is called. This will be the last thing that happens.
Upvotes: 1