gpt4 book ai didi

javascript - 如何在类外访问 Aurelia EventAggregator?

转载 作者:行者123 更新时间:2023-11-29 18:00:25 25 4
gpt4 key购买 nike

我正在尝试在模块级别而不是从类内部访问 Aurelia EventAggregator 服务。它在一个类中工作正常,我在其中 @inject 事件聚合器,但在外部不行。

import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class PingerClass {

constructor(eventAggregator) {
this.EA = eventAggregator;
}

ClassPing() {
this.EA.publish('ping','Ping from class');
// ^--- this works fine!
}
}

function ModulePing() {
EventAggregator.publish('ping','Ping from module');
// ^-------- this doesn't work!
}

那么如何在模块中访问该服务器的实例呢?我什至应该尝试这样做吗??

最佳答案

EventAggregator 类/构造函数没有任何静态方法。 EventAggregator.publish(... 将不起作用。您需要一个 EventAggregator 实例,并且需要将同一个实例用于发布和订阅 (多个事件聚合器实例可以存在于同一个应用程序中)。

主要问题是将依赖注入(inject) (@inject) 模式与全局模式混合是很棘手的。一种选择是将 DI 排除在外:

import {EventAggregator} from 'aurelia-event-aggregator';

const bus = new EventAggregator();

export function publishPing() {
bus.publish('ping','Ping from module');
}

export function subscribePing(callback) {
return bus.subscribe('ping', callback);
}

我会说你使用“PingerClass”的路线将是一种更惯用的 Aurelia 方法。

还有一个 mixin 可以将 EventAggregator API 表面添加到任何对象:https://github.com/aurelia/event-aggregator/blob/master/src/index.js#L133


编辑

假设您要使用事件聚合器发布事件以响应浏览器事件。以下是您将如何做到这一点:

ma​​in.js

import {EventAggregator} from 'aurelia-event-aggregator';

export function configure(aurelia) {
... standard aurelia main.js configure code ...

let ea = aurelia.container.get(EventAggregator); // get or create the singleton instance managed by the container.
addEventListener('beforeunload', event => ea.publish('some event', 'some payload'));
}

关于javascript - 如何在类外访问 Aurelia EventAggregator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com