0

I'm using typescript with a regular JavaScript library. The library requires setting a callback function for update notifications. The callback is executing but 'this' is undefined so I can't access any properties of MyComponent within the callback. I'm new to typescript so I don't understand what the problem is.

import { Component, OnInit } from '@angular/core';

export class MyComponent implements OnInit {

  myObject:any ={};

  constructor() { };

  libraryCallback(newObject){

    //callback is made but 'this' is undefined  
      this.myObject = newObject;
  }

  ngOnInit() {

    jsLibrary.setCallback(this.libraryCallback);

  } 

}
ddrjca
  • 472
  • 2
  • 15
  • 2
    You can either define the callback as an arrow function: `libraryCallback = (newObject) => { ... }` or bind the context: `jsLibrary.setCallback(this.libraryCallback.bind(this));`. – ConnorsFan Apr 10 '19 at 18:13
  • ^^^ or `jsLibrary.setCallback((e) => this.libraryCallback(e));` – Reactgular Apr 10 '19 at 18:15

0 Answers0