Creating a global App object

In notebook:
Building Modern Web Apps
Created at:
React libraries JavaScript Ampersand
Addressing the issue he mentioned earlier: the ​app​ variable he used before (for the history management) is not explicit for other developers, it was not declared in the module, so wasn’t clear where it came from. ("No magic" principle)
It came from inside app.js declared as ​ = {...}
Not a good solution.

We could just default export​ - but there are some timing issues, (race conditions). 

Or we could create a file app-global.js that just holds an empty object (​export default {}​) These modules are cached, so all other modules that use have the same object, so can extend it. This is the concept of a singleton. This could be a good solution.

The ampersand-app does this same thing with just an extend method to mixin more things. And a reset function for unit tests. And the app global is also an event-emitter so you can send signal throughout your app (​app.trigger​). Useful for metrics. Warns that it (message bus) can create a mess if overused.

So now in app.js we can use ampersand-app
  // **** app.js ****
import Router from './router'
// ++++ 1. import ampersand-app
import app from 'ampersand-app'

// ---- 2. instead of = {
// = {
// ++++ 3. use app.extend()
    init () {
      this.router = new Router();


// ++++ 4. assing app to to
// be able to use it in the console = app
Then in other modules, where he needs these "global" methods (like router.history) he imports the same ampersand-app module.


In any module that imports ampersand-app :
​app.trigger('local', {some:'data'})

Then in another module
app.on('local', () => console.log(arguments))​ 

He proposes to use it for metrics tracking (not much else...)
You can also use ​app.on('all', function(eventName, payload){...​