Tinadm
Tinadm

Reputation: 369

How to sync Aurelia EventAggregator with ViewModel lifecycle

Basically I'm trying to navigate between two view (let's call them view1 and view2) models using Router.navigate function. I need to pass some data from view1 to view2 during navigation and for that I'm using event Aurelia's event aggregator like described bellow. Also, view2 has a ref item I need to access inside the subscription event.

View1

...
this.router.navigate("view2").then(() => {
    console.log("Publishing message");
    this.eventAggregator.publish(new ShareDataMessage(dataToShare));
});

View2

...
attached() {
    console.log("View attached");
    console.log("RefItem 1: " + this.refItem);
    this.eventAggregator.subscribeOnce(ShareDataMessage, message => {
        console.log("Event received")
        console.log("RefItem 2: " + this.refItem);
    });
}

However, if I run the app, and navigate from view1 to view2, i get the following output:

Publishing message
Event received
RefItem 2: null
View attached
RefItem 1: [object HTMLImageElement]

Obviously this was not the execution flow I expected. Can someone please explain me what I'm missing?

Upvotes: 1

Views: 564

Answers (1)

Ashley Grant
Ashley Grant

Reputation: 10887

I've been unable to replicate your console log flow in Chrome 48. I will say that maybe you should consider placing the subscribeOnce call in the class's constructor to make sure the EventAggregator is aware of your subscription at the earliest possible time.

Please be aware that attached is part of the Component lifecycle and not part of the Router's page lifecycle, and thus you might be better off using the activate method instead of attached for whatever you are doing in this case. I can't be sure which is the correct method for your use case without more context, but you might want to double check. I should be available today on Gitter if you'd like to PM me for some more help.

Upvotes: 1

Related Questions