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:

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director and Oracle Developer Champion. Solution architect and developer on diverse areas including SQL, JavaScript, Kubernetes & Docker, Machine Learning, Java, SOA and microservices, events in various shapes and forms and many other things. Author of the Oracle Press book Oracle SOA Suite 12c Handbook. Frequent presenter on user groups and community events and conferences such as JavaOne, Oracle Code, CodeOne, NLJUG JFall and Oracle OpenWorld.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.