user1511417
user1511417

Reputation: 1940

Javascript image onload callback class-intern function

Objekt.prototype.loadImg = function(pImg){
    if(pImg!=null){
        this.imgLoaded=false;
        this.img = null;
        this.img = new Image();         
        this.img.src = pImg;     
        this.img.onload = function(){
            alert("!");
            this.autoSize();                
            this.imgLoaded=true;
        }; 

    }
}

My Problem is that "this" is invalid in the "onload = function()"-function!

alert("!"); is executed, but not the Objekt.prototype.autoSize()-function for example!

What do I have to do to call my "class-intern"-functions (e.g. autoSize) ???

Upvotes: 1

Views: 1104

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382167

That's because the onload function isn't called with your objekt as receiver. So this, inside this callback, isn't the desired object.

You can do this to transmit this to the onload callback :

Objekt.prototype.loadImg = function(pImg){
    if(pImg!=null){
        this.imgLoaded=false;
        this.img = null;
        this.img = new Image();         
        this.img.src = pImg;     
        var _this = this;
        this.img.onload = function(){
            alert("!");
            _this.autoSize();                
            _this.imgLoaded=true;
        }; 
    }
}

Upvotes: 1

Related Questions