Access the original calling context in a callback function in TypeScript

Lucas Jellema

While working on my Ionic 2 application, I made use of the exif.js library (for extracting meta-data from image files). Some of the key functions in this library are called and passed a callback function that is invoked when the image has been analyzed. From this callback function, I wanted to invoke a function (TypeScript method) defined in my class. Inside the callback function however, I did not have access to the calling context. Inside the callback function, this referred to the object passed into the callback function – and not to what this referred at the point of making the call to EXIF:

image

It took me some wondering, experimenting, mild cursing and browsing to figure out how to resolve this issue. Using some threads on StackOverflow, I worked out a solution. The callback function is produced by a helper method that produces the callback function and in doing so injects context references into it. Any parameters passed into this method are available as context inside the callback function. In this example, a parameter called outerThis of type AddBeadModal – the class this code resides in – is expected. Any elements defined on this class are now accessible inside the callback function, as is demonstrated with the call to convertDegToDec and the reference to the location property.

Code for exifHandleGetData – the helper method that produces the callback function:

image

When the call is made to EXIF, the result from the call to exifHandleGetData(this) is passed to EFIX as the callback function. This parameter carries references to the calling scope – through the parameter this.

Code for handlePictureSelection – the method that receives an update to an input type=file component and has EXIF process the selected image (and updates an Angular 2 form component subsequently.

image

 

Resources

This thread on StackOverflow helped me deal with my challenge: http://stackoverflow.com/questions/14471975/how-can-i-preserve-lexical-scope-in-typescript-with-a-callback-function.

Next Post

Saving money by understanding Oracle licensing, part 1

Facebook0TwitterLinkedinOracle and licenses. The general feeling most of the time is that you pay too much for the use of the Oracle products, and it’s not always sure if you are compliant, because of the complexity of the rules. This – hopefully clarifying –  blog is part of a small […]