user550
user550

Reputation: 338

Access variable within callback function

Hi I have the following code where I am calling a function that takes a callback function that takes a parameter. Basically I am trying to get the contents of e into this.items but I cant escape the callback function?

function stash(){
    this.items = new Array();

    this.get = function(){
      opr.stash.query({},function(e){
         console.log(this.items); //this is not defined
      });
    }
}

s = new stash();
s.get();

Upvotes: 0

Views: 69

Answers (3)

Christopher
Christopher

Reputation: 1377

I ran into a similar problem in d3.chart.

I don't have access to opr.stash at the moment so i couldn't test this first, but have you tried something like the following:

function stash()
{
    var myStash = this;

    myStash.items = new Array();

    myStash.get = function(){
       opr.stash.query({},function(e){
       console.log(myStash.items); //this is not defined
      });
    }
}

s = new stash();
s.get();

Upvotes: 0

Alex Wolfe
Alex Wolfe

Reputation: 39

this is no longer in scope on the callback so make a reference to it that you can user later. The .bind(this) is a good solution in modern browsers but may fail in older versions of Internet Explorer as that method may not be available.

function stash(){
        var self = this; 
        this.items = new Array();

        this.get = function(){
          opr.stash.query({},function(e){
             console.log(self.items); 
          });
        }
    }

Upvotes: 0

raina77ow
raina77ow

Reputation: 106483

Problem: callback function's context object (this) no longer refers to the context object of get() method.

Solution: bind your callback function to the target object, like this:

opr.stash.query({},(function(e){
  console.log(this.items);
}).bind(this));

Upvotes: 2

Related Questions