用于打字稿的强类型事件包。如何将绑定处理程序添加到事件
Strongly typed events package for typescript. How to add bound handelers to an event
我在我的应用程序中使用 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(component) 方法。
onUpdate.sub(component.Update.bind(component));
这是一个解决方案,但现在我在退订时遇到问题。如果我尝试取消订阅完全相同的绑定方法,就像您想要普通方法一样,它不会取消订阅。我的猜测是它无法将绑定方法相互比较。这总是导致我的方法仍然被订阅。
我可以尝试任何替代方案或解决方案吗?
查看代码,该库混淆了订阅签名的回调函数。
在适当的 subscribe->cancel
架构中,方法 subscribe
应该总是 return 一个 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();
我在我的应用程序中使用 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(component) 方法。
onUpdate.sub(component.Update.bind(component));
这是一个解决方案,但现在我在退订时遇到问题。如果我尝试取消订阅完全相同的绑定方法,就像您想要普通方法一样,它不会取消订阅。我的猜测是它无法将绑定方法相互比较。这总是导致我的方法仍然被订阅。
我可以尝试任何替代方案或解决方案吗?
查看代码,该库混淆了订阅签名的回调函数。
在适当的 subscribe->cancel
架构中,方法 subscribe
应该总是 return 一个 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();