我在用Aurelia Framework
with Typescript
并在event aggregator
我能够发布和订阅频道。
问题是我无法取消订阅频道。
注意:所有形式的 subscribe 方法都会返回一个 dispose 函数。您可以调用该函数来销毁订阅并停止接收消息。一个好的处理位置是在视图模型的停用回调中(如果它由路由器管理),或者在其分离的回调中(如果它是任何其他视图模型)。
这是取自aurelia 官方文档网站 http://aurelia.io/docs.html#the-event-aggregator我似乎不太明白如何实现这一点。
我去了奥里莉亚吉特频道 https://gitter.im/Aurelia/Discuss我发现了 3 个与此相关的讨论,其中一个给出了以下取消订阅的示例:
sub = ea.subscribe();
//unsubscribe the event
sub();
问题是这段代码在 TypeScript 中不起作用。
我如何取消订阅event aggregator
在打字稿中?
现在,使用这段代码
@inject(Publisher, Subscriber)
export class Home {
publisher: Publisher;
subscriber: Subscriber;
channelName = "testChannel";
constructor(pub: Publisher, sub: Subscriber) {
this.publisher = pub;
this.subscriber = sub;
this.subscriber.subscribe(this.channelName);
this.publisher.publish(this.channelName, "Ana are mere");
}
}
@inject(EventAggregator)
export class Publisher {
eventAggregator: EventAggregator = null;
constructor(agg: EventAggregator) {
this.eventAggregator = agg;
}
publish(channelName: string, object: Object) {
this.eventAggregator.publish(channelName, object);
}
}
@inject(EventAggregator)
export class Subscriber {
eventAggregator: EventAggregator = null;
constructor(agg: EventAggregator) {
this.eventAggregator = agg;
}
subscribe(channelName: string) {
this.eventAggregator.subscribe(channelName, object => {
//TODO do something with received object
alert(object);
});
}
unsubscribe(channelName: string) {
debugger;
}
}
当执行Home
在组件中, subscribe 方法不会只执行一次,而是与构造函数被调用的次数一样多。所以,如果我进入主页 3 次,它就会被执行 3 次。
所以:
为什么我的订阅者方法被多次触发?
我如何取消订阅event-aggregatoor
在打字稿中?
Thanks!