Reputation: 8375
I have a class like this
var grid = function () {
this.cell = null;
this.loadImage = function () {
var image = new Image();
var object = this;
image.src = "blah";
$(image).load(function () {
object.cell = this;
});
}
this.showImage = function () {
alert(object.cell); // This should print [object Object] ... but it print null;
}
}
The showImage function is called after the image called loaded from loadImage function. Does anyone know why object.cell is null... I have reference to this object in loadImage.
Upvotes: 1
Views: 116
Reputation: 1637
This is what I think you should be doing:
var grid = function () {
this.cell = null;
this.loadImage = function () {
var image = new Image();
image.addEventListener("load", (function (obj) {
return function () {
obj.cell = this;
};
})(this));
image.src = "http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg";
}
this.showImage = function () {
alert(this.cell);
}
}
Upvotes: 1