简体   繁体   中英

Backbone.js Scope

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM