Reputation: 338
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
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
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