Search code examples
javascriptbackbone.jsmarionetteoffline

Setting a variable in Backbone Marionette app


I'd like to assign a value to a variable like "down" when network connectivity is lost. However, I'm not sure where and how to set the variable in Backbone so that it is accessible from any view or model. I'm new to Backbone and Marionette. This variable will be useful for modules that are doing a REST endpoint call.

In AngularJS, I can either set an http interceptor or as a service/factory but not sure how to do it in BackboneJS Marionette app.

if (networkStatus !== 'down') {
   // do the backbone.fetch()
}

Also, is my idea a good approach?


Solution

  • You can use Backbone.Radio, and set up a globalState channel:

    var globalStateChannel = Backbone.Radio.channel('globalState')
    if(globalStateChannel.request('networkStatus') !== 'down'){ ... }
    

    Somewhere in you App, you should set up the reply handler:

    var globalStateChannel = Backbone.Radio.channel('globalState')
    globalStateChannel.reply('networkStatus', function(){
      // put your logic here
      return something
    }
    

    Of course, explicitly referencing the channel every time is awfully long - you'd do it at Viewss initialisation, but this is food for thought ^^