jeudi 4 mai 2017

typescript singleton design pattern : this is undefined

I've implemented the singleton pattern in a typescript ( 2.1.6 ) class as follows:

export class NotificationsViewModel {
    private _myService: NotificationService;
    private _myArray: [];
    private static _instance: NotificationsViewModel;
    private constructor() {
        this._myService = new NotificationService();
        this._myArray = [];
        NotificationsViewModel._instance = this;
    }
    public static getInstance(): NotificationsViewModel {
        if (!this._instance) {
            this._instance = new NotificationsViewModel();
        }
        return this._instance;
    }
    public startListening() {
        return this._myService.addUserNotificationChildListener(this.handleNotifications);
    }
    private handleNotifications(notification: Models.NotificationItem) {
        this._myArray.push(notification);// this line breaks
    }
}

Interestingly the handleNotifications method fails with error cannot read property _myArray of undefined. Basically it's saying that this - which equals instance is not instantied (correct ? ). What I don't understand is how this is possible, as this._myService is used without any problem. Am I implementing the pattern in the wrong way? Why am I getting that error?

Aucun commentaire:

Enregistrer un commentaire