0

I’m trying to find out a way to creating a custom view-model and making its functions accessible from a page within the main router-view element. This custom view-model, in my case called "secondbar" is supposed to be located under main nav-bar and should contain a login status ("Logged in as ..." / "Not logged in").

In my router-view, one of the pages is a login page. After successful login, I want to be able to call a function of "secondbar" directly in order to change the login status there without page refresh.

I tried to inject "secondbar" class in login.js file; this way I can access the functions, but the message on the page wouldn't change (it seems like I'm accessing another instance of "secondbar"). I also tried to print out the same message directly on the main nav-bar, but it seems like this is not the right approach and it didn’t work either.

Is there some way, how I can access a "secondbar" class directly (the same instance is being shown in the browser) and call a function located there from a page inside a router-view?

App.html

<template bindable="router">
  <require from="secondbar/secondbar"></require>

  <!-- navbar -->

  <secondbar view-model.ref="secondbar"></secondbar>

   <router-view>
    <!—- page content -->
  </router-view>
</template>

App.js

import {Redirect} from 'aurelia-router';
import {inject} from 'aurelia-framework';

export class App {

configureRouter(config, router) {
    this.router = router;
    config.title = ‘’;
    config.map([
        { route: [''], name: 'home', moduleId: 'home/index', nav: true, title: 'Home' , settings: { roles: [''] }},
        { route: 'login', name: 'login', moduleId: 'login/login', nav: true, title: 'Log In', settings: { roles: [''] }},
    ]);
}
}
Jesse
  • 3,522
  • 6
  • 25
  • 40
George P.
  • 181
  • 1
  • 8

1 Answers1

0

What you could do is create a login-service or something similar, where you can bind to in both the secondbar and the login page-view. The basic would look like this:

login-page:

import login-service from "/login-service/login-service";

// inject    

login() {
  // do login stuff
  this.loginService.currentUser = user; // user would be any object of choice
}

secondbar.js:

import login-service from "/login-service/login-service";

// inject    

secondbar.html

<span if.bind="loginService.currentUser">
  Logged in as: ${loginService.currentUser.username}
</span>
<span if.bind="!loginService.currentUser">
  Not logged in
</span>
Jesse
  • 3,522
  • 6
  • 25
  • 40