Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference 'this' is null on $rootScope.$on

Declared the following constructor in my Typescript AngularJS controller.

static $inject: Array<string> = [
    '$rootScope',
    'BookingRepository'
];
constructor(
    $rootScope: ng.IRootScopeService,
    bookingRepository: soft.data.BookingRepository
) {
    super();

    this.$rootScope = $rootScope;
    this.$rootScope.$on('accessController_onNavAccessSelected', this.accessController_onNavAccessSelected);

    this.bookingRepository = bookingRepository;
}

BUT when accessController_onNavAccessSelected is called, I'm getting null when I reference 'this'. I'm expecting the instance of the controller.

// Listening Events
accessController_onNavAccessSelected(event: ng.IAngularEvent, accessViewModel: soft.data.AccessViewModel): void {
    console.log(this);
}

What did I missed? Or How do I get a reference on the instance of my controller?

like image 667
JeeShen Lee Avatar asked Sep 08 '26 11:09

JeeShen Lee


1 Answers

The context of the keyword this changes when using callbacks.

To prevent that, add .bind(this):

this.$rootScope.$on('accessController_onNavAccessSelected', this.accessController_onNavAccessSelected.bind(this));

or just use arrow function of ES6:

accessController_onNavAccessSelected = (event: ng.IAngularEvent, accessViewModel: soft.data.AccessViewModel) => {
    console.log(this);
}
like image 54
Faly Avatar answered Sep 11 '26 00:09

Faly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!