RequireJs - loading values ​​from one dependency as a parameter for another dependency

We wrapped the Google Maps API as an asynchronous module in RequireJs.

define(['async!http://maps.googleapis.com/maps/api/js?libraries=places&key=APIKEY&sensor=true'], function(){ var maps = window.google.maps; return maps; }); 

Now we want to extract the API key in the config.js file in order to save the configuration settings for different environments. But this cannot work in any way (since the variable name is not yet defined)

 define([config, 'async!http://maps.googleapis.com/maps/api/js?libraries=places&key' + config.APIKEY + '&sensor=true'], 

I tried to do double nesting of define () and require () to no avail. How to write a chain of dependencies to achieve the desired effect?

+4
source share
1 answer

The only way I can think now is to include a callback. Sort of:

 define([], function() { var exports = {}; exports.Maps = function (maps) { this.hello = function () { console.log(maps); }; }; exports.Factory = function (apiKey) { this.manufacture = function (loadedCallback) { require(['http://maps.googleapis.com/maps/api/js?libraries=places&key=' + apiKey + '&sensor=true'], function () { loadedCallback(new exports.Maps(window.google.maps)); }); }; }; return exports; }); 

Then, to use it, you must:

 require(["foo"], function (Foo) { var apiKey = "blablabla", factory = new Foo.Factory(apiKey); factory.manufacture(function (Maps) { Maps.hello(); }); }); 
0
source

All Articles