In appscript we call functions all the time.
Theses interdependencies can cause trouble over time ðŸĪŠ.

The good news is: we can separate concerns by introducing events:

Not interested in events (yet), but still curious about appscript? Read how to teach yourself appscript here

Here are some tips to organize your appscript-code using an eventbus.

It separates hardcoding from softcoding.

Why would i want this?

Stability

The more code we add, the more we want to be careful right?
Other reasons are:

  • hotplugging of features ⚡
  • keep functions tiny 🌷
  • intercepting or extending existing features ⚛
  • more control over importing code in appscript 🚚

Hello appscript eventbus.

  var eventbus = function(o){
    o.events = {}
    o.emit = function(e,val){
      Logger.log("emit('"+e+"')")
      var evs = o.events[e] || []
      evs.map( function(f){ if( f ) f(val) } )
      return o
    }
    o.on = function(e,f){
      var evs = o.events[e] || []
      evs.push(f)
      o.events[e] = evs
      return o
    }
  }
  new eventbus(this)

Put the above snippet in your editor

Register some listeners

this.on('init',function(opts){
  Logger.log("featureA"+opts)
})

this.on('init',function(opts){
  Logger.log("featureB"+opts)
})

function init(){
  this.emit("init",{a:1}) 
}

Now lets run it

Voila! Have fun with eventdriven programming!

The flow of our code is more dynamic now.

Further reading