My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is 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);// encountering an error on this line
}
}
There is an issue where the handleNotifications
method throws an error message
. It seems that cannot read property _myArray of undefined
this
, which should refer to the instance
, is not instantiated (correct?). I find it puzzling because this._myService
is working fine.
Could my implementation of the pattern be incorrect? What could be causing this problem?
EDIT Below is the code snippet that calls the class:
notificationsViewModel = NotificationsViewModel.getInstance(mainUser);
notificationsViewModel.initialize().then(() => {
notificationsViewModel.startListening();
}).catch((error) => {
console.dump(error);
});
I have omitted the initialize
method from the provided snippet, but it returns a promise.