Aurelia取消订阅Event Aggregator

rad*_*tei 16 typescript aurelia aurelia-event-aggregator

我正在使用Aurelia Framework,Typescript并且event aggregator我能够发布和订阅频道.

问题是我无法取消订阅频道.

注意:所有形式的subscribe方法都返回一个dispose函数.您可以调用此函数来处理订阅并停止接收消息.如果由路由器管理,则处置视图模型的停用回调的好地方,或者如果它是任何其他视图模型,则在其分离的回调中.

这取自aurelia官方文档网站,我似乎并不了解如何实现这一点.

我进入了aurelia gitter频道,我找到了3个关于此的讨论,其中一个给出了以下取消订阅的示例:

sub = ea.subscribe();

//unsubscribe the event
sub();
Run Code Online (Sandbox Code Playgroud)

问题是此代码在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在执行Home组件时,订阅的方法不会执行一次,而是执行cosntructor的次数.所以,如果我已经在主页上3次,它将被执行3次.

那么:为什么我的订阅者方法多次被触发?如何取消订阅event-aggregatoorTypeScript?

谢谢!

Jer*_*yow 25

2015年10月14日编辑

EventAggregator类的subscribe函数返回一个"dispose"函数 "subscription"对象:

var subscription = eventAggregator.subscribe('some event', value => alert(value));
Run Code Online (Sandbox Code Playgroud)

您需要保留对订阅对象的引用,以便在不再需要时销毁订阅.

在视图模型中,订阅事件的最佳时机就是它attached.同样,取消订阅的最佳时机就是它detached.

以下是您Home使用此模式时视图模型的样子(注意:我已经删除了Subscriber和Publisher类,因为我认为它们会在EventAggregator周围添加不​​必要的复杂性,并且很难解释您的问题的解决方案).

@inject(EventAggregator)
export class Home {
  eventAggregator: EventAggregator;
  subscription: { dispose: () => void };

  constructor(eventAggregator: EventAggregator) {
    this.eventAggregator = eventAggregator;
  }

  attached() {
    this.subscription = this.eventAggregator.subscribe('some event', value => alert(value));
  }

  detached() {
    this.subscription.dispose();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这在Aurelia的10月发布中更新.订阅调用现在返回一个订阅对象,您可以在其上调用dispose()方法来终止订阅. (2认同)