0

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();
1

3 Answers 3

2

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));
Sign up to request clarification or add additional context in comments.

Comments

0

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); 
          });
        }
    }

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.