I have two views on the same page. View A’s view-model needs to call a method in view B’s view-model. Is that possible with Aurelia?
Also, is this the best approach? Would it be better to use the EventAggregator (pub/sub) to communicate between the view-models?
----- More Details -----
To be much more specific, there is a nav bar used in my app.html file like this:
<template>
<require from="nav-bar-view"></require>
<nav-bar-view></nav-bar-view>
<router-view></router-view>
</template>
View-models within the router-view need to be able to change the nav bar's title and button text.
My initial design was to use pub/sub to communicate the changes to the nav bar view-model. Since that seemed a bit messy and overcomplicated, I wanted to come up with a simpler approach.
My latest idea is to create a singleton NavBar class that is injected into the NavBarView class and the "consumer" view-models.
The following is a simplified version of the code:
nav-bar-view.html:
<template>
<div class="center">${navBar.title}</div>
</template>
nav-bar-view.js:
import {inject} from 'aurelia-framework';
import {NavBar} from 'nav-bar';
@inject(NavBar)
export class NavBarView {
constructor(navBar) {
this.navBar = navBar;
}
}
nav-bar.js:
import {singleton} from 'aurelia-framework';
@singleton()
export class NavBar {
constructor() {
this.title = '';
}
}
view.js (a consumer of the nav bar):
import {inject} from 'aurelia-framework';
import {NavBar} from 'nav-bar';
@inject(NavBar)
export class View {
constructor(navBar) {
this.navBar = navBar;
}
attached() {
this.navBar.title = 'This View's Title';
}
}
Again, this is much simpler than the actual code, but it servers to illustrate the idea.
I've tried it out and it works fine. Does this make sense? Is there a better way?