Tim Lupo Tim Lupo - 2 months ago 9
TypeScript Question

Typescript Nested This Not Calling Defined Function

I'm working on an app using Ionic 2 Beta and Typescript. I'm hitting some sort of error from the way

this
interacts when nested in Typescript, but I can't quite get my head around it. Here is my code:

constructor(public navCtrl: NavController, params: NavParams, platform: Platform) {
platform.ready().then((readySource) => {
try {
this.num = params.get("num");
this.unprocData = params.get("data");
var image = <HTMLImageElement>document.getElementById('unprocImg');
image.src = this.unprocData;
image.onload = function() { console.log("images loaded"); this.proc(this.num); }
//some stuff
} catch (err) {
console.log("Problem Starting Render // " + err);
this.navCtrl.push(IndexPage);
}
});
}

proc(num) {
try {
console.log("starting render...");
switch(num) {
case 0:
this.procImg1(function() { //process the image for default vintage greyscale
this.load(this.procData, this.descriptionPoster1, "assets/img/Poster1.png", 250, 310, .6, .6);
}); break;
..
}
} catch (err) {
console.log("Problem Starting Render // " + err);
this.navCtrl.push(IndexPage);
}
}

test() {
this.proc(0);
}


Interestingly, the function
test()
works as expected, but when calling
this.proc(..)
from inside of the
image.onload(..)
I get the error
this.proc is not a function
. How can I solve this? Thanks.

Answer

The problem is that the this is different when this:

image.onload = function() { console.log("images loaded"); this.proc(this.num); }

Is executed, and that's because the regular function that you are using does not save the context for this for when it is executed (it's asynchronous).

You can do:

(1) Use the arrow function as you have above that:

image.onload = () => { console.log("images loaded"); this.proc(this.num); }

(2) Use bind:

image.onload = function() { console.log("images loaded"); this.proc(this.num); }.bind(this)
Comments