Creating a global App object

In notebook:
Building Modern Web Apps
Created at:
2016-01-22
Updated:
2016-06-12
Tags:
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 ​window.app = {...}
Not a good solution.

We could just default export window.app​ - 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 window.app = {
//window.app = {
// ++++ 3. use app.extend()
app.extend({
    init () {
      this.router = new Router();
      this.router.history.start();
    }
})

app.init();

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

Messaging

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){...​