LittleFunny
LittleFunny

Reputation: 8375

javascript: How to reference a class from event

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

Answers (2)

caleb
caleb

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

Matt Ball
Matt Ball

Reputation: 359776

object is undefined in showImage.

Upvotes: 4

Related Questions