I'm trying to access the Aurelia EventAggregator service at a module level, rather than from inside a class. It's working fine from within a class, where I @inject the event aggregator, but not outside.
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!
}
So how do I access the instance of that server in the module? Should I even be trying to do so??
The EventAggregator class/constructor-function doesn't have any static methods. EventAggregator.publish(... won't work. You'll need an instance of the EventAggregator and the same instance will need to be used for both publishing and subscribing (multiple event aggregator instances can exist in the same app).
The primary issue is mixing dependency injection (@inject) patterns with global patterns is tricky. One option would be to take DI out of the picture:
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);
}
I'd say the route you went with the "PingerClass" would be a more idiomatic Aurelia approach.
There's also a mixin that will add the EventAggregator API surface to any object: https://github.com/aurelia/event-aggregator/blob/master/src/index.js#L133
EDIT
let's say you want to publish an event using the event aggregator in response to a browser event. Here's how you would do that:
main.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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With