I'm rebuilding the Atlassian React+Flux tutorial in TypeScript (using bindings of React, Flux and Node from tsd) but I'm encountering a problem with implementing the dispatcher, which essentially is a singleton.
I'm trying the following:
AppDispatcher.ts
export var instance = AppDispatcher.getInstance();
class AppDispatcher extends Flux.Dispatcher<AppPayload> {
private static _instance:AppDispatcher = new AppDispatcher();
constructor() {
super()
if(AppDispatcher._instance){
throw new Error("Error: Using this constructor should not be possible...WTH javascript");
}
AppDispatcher._instance = this;
}
public static getInstance():AppDispatcher
{
return AppDispatcher._instance;
}
...
}
Like in the tutorial I use a JSON file on localStorage to fake a web API. So my ActionCreator does the following:
ActionCreator.ts
import AppDispatcherInstance = require('../dispatcher/AppDispatcher');
//ActionCreator
//In Flux ActionCreators
export function receiveAll(rawNodes:any) {
AppDispatcherInstance.instance.handleServerAction(AppDispatcherInstance.ActionIdentifier.REFRESH_FROM_SERVER, rawNodes)
}
Unfortunately I get a runtime exception Uncaught TypeError: Cannot read property 'getInstance' of undefined pointing to the transpiled Javascript line
exports.instance = AppDispatcher.getInstance();
- Am I implementing the singleton wrong in TypeScript?
- Is there a better way in general to do this? I thought about not writing a class at all and to the singleton by only exporting certain functions (like recommended in other SO questions) but I still want to extend the Flux.Dispatcher class?