Access the original calling context in a callback function in TypeScript image 9

Access the original calling context in a callback function in TypeScript

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:


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:


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.




This thread on StackOverflow helped me deal with my challenge: