Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create Environment Variables for backbone applications?

Tags:

backbone.js

We are building a backbone application that uses a set of REST APIs. What we want to do ideally is to have different config files for dev and live that are determined by environment variables. Is it possible.

Thanks in advance

like image 757
user1521903 Avatar asked Jul 12 '12 20:07

user1521903


1 Answers

I recommend you to have one file in a way like this:

var YourProject = {};
YourProject.Config = {
   Local : {
     db : 'mysql:dumy:dummy@localhost',
     relativeUrl : 'blabla',
     otherConfig : '123456'
   },
   Dev : {
     db : 'mysql:dumy:dummy@localhost',
     relativeUrl : 'blabla',
     otherConfig : '123456'
   },
   Production : {
     db : 'mysql:dumy:dummy@localhost',
     relativeUrl : 'blabla',
     otherConfig : '123456'
   }
}

And then in your utilities to have something like this:

YourProject.ConfigHandler = {
  getValue : function(key){
    var env;
    switch( window.location.hostname ){
      case "localhost":
      case "127.0.0.1":
        env = 'Local';
        break;
      case "dev.yourdomain.com":
        env = 'Dev';
        break;
      case "yourdomain.com":
        env = 'Production';
        break;
      default:
        throw('Unknown environment: ' + window.location.hostname );
    }
    return YourProject.Config[env][key];
  }
};

So you will have just one file and for call differents API DB urls you will need to call just one line:

YourProject.ConfigHandler.getValue( 'db' );
like image 87
Daniel Aranda Avatar answered Sep 30 '22 11:09

Daniel Aranda