我在我的应用中使用了strongly typed events包。这个包对于它的事件以及它处理这些事件的方式非常有用。我在我的应用程序中使用了这样的包。
let onUpdate = new SignalDispatcher = new SignalDispatcher();
let component = new Component();
onUpdate.sub(component.Update);
void Update(){
this.onUpdate.dispatch();
}
class Component {
public Update(){
//do stuff
}
}这只适用于一件事。如果您尝试在组件更新功能中访问"this“。你得到的不是组件,而是事件。因此,我尝试了function.bind(组件)方法,如下所示。
onUpdate.sub(component.Update.bind(component));这是一个解决方案,但现在我有一个问题,取消订阅。如果我尝试取消订阅完全相同的绑定方法,就像您想要正常方法一样,它不会取消订阅。我的猜测是它不能相互比较绑定的方法。这总是导致我的方法仍然被订阅。
我可以尝试任何替代方案或解决方案吗?
发布于 2020-03-10 15:45:36
从代码中可以看出,该库混淆了订阅签名的回调函数。
在适当的subscribe->cancel体系结构中,方法subscribe应该始终返回Subscription对象,以允许以一种安全的方式取消订阅。
由于这个问题已经公开了一段时间,我将推荐一个替代事件库sub-events供您考虑。
对于信号,根据那里的Signals页面,我们可以定义一个通用的信号类型:
class Signal extends SubEvent<void> {} // reusable Signal type然后我们可以将您的代码更新为:
const onUpdate = new Signal();
const component = new Component();
// you can bind an event to the right context in 2 ways:
const sub = onUpdate.subscribe(component.Update.bind(component));
// or alternatively:
const sub = onUpdate.subscribe(component.Update, {thisArg: component});
void Update() {
this.onUpdate.emit(); // emit the event (signal)
}
class Component {
public Update(){
//do stuff
}
}然后,当您需要取消订阅时,您只需执行以下操作:
sub.cancel();https://stackoverflow.com/questions/59664493
复制相似问题