Reputation: 4468
I have a parent-child component architecture in my Aurelia app. Panel
is a Parent component View-model, inside which there is a Tool
component.
I have a pagination UI on Panel
, clicking on which the Tool
should update. The problem is, the variable which keep track of which page number was clicked, pageNumber
is only available in panel.ts
and not available in tool.ts
. So basically, this is an issue of communicating between two ViewModels.
To solve this issue, I am using Aurelia's EventAggregator
by following this excellent tutorial. Here is what I have written till now:
panel.html
<a class="page-link" click.delegate="pageClick(1)"> 1 </a>
panel.ts
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';
@inject(EventAggregator)
export class Panel {
eventAggregator: EventAggregator;
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
pageClick(pageNumber) {
var pageInfo = {
pageNumber: pageNumber
}
this.eventAggregator.publish("pageClicked", pageInfo);
}
tool.ts
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';
@inject(EventAggregator)
export class Tool {
eventAggregator: EventAggregator;
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
pageClicked() {
this.eventAggregator.subscribe("pageClicked",
pageInfo => {
console.log(`${pageInfo.pageNumber} was clicked`);
});
}
This works fine until the event is fired. I tried debugging and saw that eventAggregator
fired the pageClicked
event. But the breakpoint on subscribe
was never hit. Somehow the subscribe
method is not triggered. What am I missing here?
My initial thought is that EventAggregator
instance is different, but I am not sure if it needs to be same. Any help is appreciated. Also, if you know some other better way to achieve intercomponent communication
please let me know how. Thanks.
Upvotes: 1
Views: 827
Reputation: 10887
You need to set up the subscription in a function that will be called. Maybe add an attached
callback and set up the subscription there. Make sure to dispose the subscription, probably in a detached
callback. I'm on mobile right now, but if you need a code example, let me know, and I'll add one when I get home.
Upvotes: 2