【发布时间】:2015-08-25 14:06:55
【问题描述】:
我正在使用Aurelia Framework 和Typescript,在event aggregator 中我能够发布和订阅频道。
问题是我无法取消订阅频道。
注意:所有形式的 subscribe 方法都返回一个 dispose 函数。您可以调用此函数来处理订阅并停止接收消息。如果视图模型由路由器管理,则可以在视图模型的停用回调中进行处理,或者如果它是任何其他视图模型,则在其分离的回调中进行处理。
这取自aurelia official documentation website,我似乎不太明白如何实现它。
我在aurelia gitter channel 上找到了 3 个关于此的讨论,其中一个给出了以下退订示例:
sub = ea.subscribe();
//unsubscribe the event
sub();
问题是这段代码在 TypeScript 中不起作用。
如何在 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 的方法不会只执行一次,而是与 cosntructor 被调用的次数一样多。所以,如果我在主页上 3 次,它将被执行 3 次。
所以:
为什么我的订阅者方法被多次触发?
如何在 TypeScript 中取消订阅 event-aggregatoor?
谢谢!
【问题讨论】:
标签: typescript aurelia