我们已将Google Maps API包装为RequireJs中的异步模块。
define(['async!http://maps.googleapis.com/maps/api/js?libraries=places&key=APIKEY&sensor=true'],
function(){
var maps = window.google.maps;
return maps;
});
现在我们希望将API密钥提取到config.js文件中,以存储不同环境的配置设置。但是这没有办法可行(因为变量名尚未定义)
define([config,
'async!http://maps.googleapis.com/maps/api/js?libraries=places&key' + config.APIKEY + '&sensor=true'],
我尝试了一些define()和require()的双重嵌套无效。如何编写依赖链以达到预期的效果?
答案 0 :(得分:0)
我现在能想到的唯一方法就是回调。类似的东西:
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;
});
然后使用它你会做:
require(["foo"], function (Foo) {
var apiKey = "blablabla",
factory = new Foo.Factory(apiKey);
factory.manufacture(function (Maps) {
Maps.hello();
});
});