Global Application State In Aurelia

Globals - Everyone hates them, but ultimately most applications require some bit of global state.

In Aurelia, your global state would basically be your variables that need to live between routes and views. A few examples that seem to come up a lot:

  • Configuration
  • Currently logged in user information

The way that I tend to manage this is to create a file called ApplicationState.js in the root of src, containing an exported ApplicationState class:

export class ApplicationState {  
  constructor () {
    this.loggedInUser = null;
    this.configuration  = {
      optionOne : false,
      optionTwo : false
    };
  }
}

You can then inject this into ViewModels throughout your application. Since Aurelia's DI defaults to treating the class as a singleton, everything works as we would want it to: If we alter something in ApplicationState, it is preserved between views.

import {inject} from 'aurelia-framework';  
import {ApplicationState} from '../ApplicationState';

@inject(ApplicationState)
export class Home {  
  constructor (appState) {
    this.appState = appState;
  }
}