我正在重建TypeScript中的Atlassian React+Flux tutorial(使用来自tsd的React,Flux和Node的绑定)但是我遇到了实现调度程序的问题,该调度程序基本上是单例。
我正在尝试以下方法:
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;
}
...
}
在教程中,我在localStorage上使用JSON文件伪造Web API。所以我的ActionCreator会做以下事情:
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)
}
不幸的是我遇到了运行时异常未捕获的TypeError:无法读取未定义的属性'getInstance'指向已编译的Javascript行
exports.instance = AppDispatcher.getInstance();
答案 0 :(得分:0)
正如评论家建议的那样,您需要移动使用该类声明之下的类的代码。类只是变量,JavaScript中的变量按顺序初始化。
通常,您不需要在TypeScript中使用显式类单例模式。见How to define Singleton in TypeScript
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();
namespace Singleton {
export function someMethod() { ... }
}
// Usage
Singleton.someMethod();
var x = Singleton; // If you need to alias it for some reason