ahmedsaber111
ahmedsaber111

Reputation: 822

Define global values using AMD require.js & backbone.js

I am developing a frontend using the Backbone.js and require.js and everything is going well till i need to create a file named it config.js to store some defaule values to use it in the whole of the application

below is the code of the config.js file

// Filename: config.js
define([''], function(){        

var baseUrl = "http://localhost:8888/client/",
apiServer = "http://api-server:8888";

return function(type){
    return eval(type);
};

});

in one of my views I would define the config.js then i can access the value of both

var baseUrl = "http://localhost:8888/client/",
apiServer = "http://api-server:8888";

via this line of code below that i put it inside any *.js file on my application

var baseUrl = config('baseUrl');
console.log(baseUrl); //prints out this > http://localhost:8888/client/

the problem here is i am using eval to get the value of what kind of value i need to retrieves, I know it's not safe method to use but could anyone suggest safe solution

Upvotes: 1

Views: 419

Answers (2)

soulcheck
soulcheck

Reputation: 36767

As an alternative solution (and uglier than Benjamin's) you can put both urls into an object:

define([''], function(){        

    var urls = {
        baseUrl: "http://localhost:8888/client/",
        apiServer: "http://api-server:8888"
    };

    return function(type){
        return urls[type];
    };

});

Still, simply exporting an object is much cleaner.

Upvotes: 1

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

RequireJS lets you define objects just like you define more complicated modules. You can have a config module and then use it in whichever other files that require it.

Inside config.js you can do:

define({
    baseUrl:"http://localhost:8888/client/",
    apiServer:"http://api-server:8888"
});

Then require it in other modules:

//someotherfile.js , defining a module
define(["config"],function(config){
   config.baseUrl;// will return the correct value here
   //whatever
});

Side note: You can use actual global state (defining the variable on window) but I strongly urge you not to since this will make testing hard, and will make the dependency implicit and not explicit. Explicit dependencies should always be preferred. In the above code and unlike the global it's perfectly clear that the configuration is required by the modules using it.

Note, if you want values that are not valid identifiers you can use bracket syntax too config["baseUrl"] the two (that and config.baseUrl) are identical in JavaScript.

Upvotes: 2

Related Questions