0

this is my function in backbone.js

var formdata = {
  name : this.$('#name').val(),
  email : this.$('#email').val()
};

this.collection.create(formdata, {
  wait : true,
  success : function(model, res) {
    var id = model.get('id');
  }
});

When I use console.log(id) inside the success function it's been displayed. But I can't access outside of the success function.

Does anyone got the answer..

Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
  • Also see the additional explanation in the answer to this: http://stackoverflow.com/questions/13301050/js-global-variable-not-being-set-on-first-iteration/13301270#13301270 – slebetman Jul 02 '13 at 08:04

2 Answers2

0

success is the closer function and you have defined id inside the function itself (var id), so by rule the variable scope is limited to success function.

try defining id outside of closer and assigned it in closer. Also assignment will be done when success is executed(asynchronous) i.e once get the response from server.

Naren Sisodiya
  • 7,158
  • 2
  • 24
  • 35
0

You can't access it because it's not set yet. The code executes before the saving has taken place. That's why you use callbacks

David Fregoli
  • 3,377
  • 1
  • 19
  • 40