0

I am using backbone and doing the following:

var self = this;
$.when(commentCollections.fetch()).done(function(comments){
  self.comments = comments;
  console.log(self.comments);
}).fail(function(){
  console.log('Could not fetch comments.');
});

console.log(this.comments);

As you can see I am trying to keep the reference of "this" in tack. self.comments refers to a "class level variable" set to [].

When I run this I get:

[]
Object {comments: Array[6]}

in the console. the [] refers to this.comments and the the Object ... refers to self.comments One might say, well do everything inside the .done() but I need, for other reason, this, what I am trying to do, concept to work.

Why is the scope of "this" not being preserved?

user3379926
  • 3,855
  • 6
  • 24
  • 42
  • callbacks are tricky of what `this` is. – Daniel A. White Jun 18 '14 at 16:19
  • 2
    It has nothing to do with `this`. Your code is **asynchronous**. `console.log(this.comments)` is executed **before** the promise is resolved, i.e. before `this.comments` is populated and the other `console.log` call is executed. – Felix Kling Jun 18 '14 at 16:20
  • i removed the close vote. – Daniel A. White Jun 18 '14 at 16:22
  • *"but I need, for other reason, this, what I am trying to do, concept to work."* if you mean accessing the values before they exist, that's simply not possible. `this.comments` will have the values you want, just not at the moment you currently trying to access them. – Felix Kling Jun 18 '14 at 16:25
  • How do I "wait" for them to exist? and then carry on? – user3379926 Jun 18 '14 at 16:28
  • By putting the code that needs the data in or call it from the `done` callback. Or, since this seems to be some kind of "class", instead of loading the data inside the constructor, pass the data as dependency to the constructor. – Felix Kling Jun 18 '14 at 16:30

0 Answers0