Javascript名称空间和条件包含

apn*_*ing 8 javascript ruby-on-rails

我用这种方式组织了一些js文件(参见源代码):

  • gmaps4rails.base.js :包含所有逻辑

    • gmaps4rails.googlemaps.js :包含函数

    • gmaps4rails.bing.js :包含与前一个文件同名的函数

所以基本上,base要求createMarkers()其在两个googlemapsbing.

从现在开始,我加载中只有一个是gmaps4rails.googlemaps.jsgmaps4rails.googlemaps.js,取决于地图API,我需要,所以它工作正常.

现在我希望能够加载所有文件(并将它们分开)但当然只包含所需地图API的代码.

基本上我想的是:

if desiredApi == "googlemaps"
   include GoogleMapsNameSpace content in BaseNameSpace
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Jai*_*ime 2

如果我理解正确的话,您只是希望能够根据用户选择(或其他一些标准)使用 google 地图 API 或 bing API 或其他 API?为此,与其尝试将正确的 API 合并到您的基础对象中,不如直接从基础对象中引用“mapService”并根据您想要的条件选择 mapService?

像这样的东西:

Map = function(service, canvasId) {
    var mapService = MapServices[service];

    return {
        initialize: function() {
            var theMap = mapService.createMap();
            mapService.render(canvasId);
        }
// more functionality for your base object (that the outside world calls) goes here

    }
}

var MapServices = MapServices || {};

MapServices.google = {
  createMap: function() {},
  render: function(canvas) {
    $("#"+canvas).html("I'm a google map");
  },
  createMarker: function(args) {}
// all your map functionality goes here calling google specific functions
};

// this could be in a different js
MapServices.bing = {
  createMap: function() {},
  render: function(canvas) {
    $("#"+canvas).html("I'm a bing map");
  }, 
  createMarker: function(args) {},
// all your map functionality goes here calling bing specific functions
}

$(function() {
  var theMap = new Map("google", "theDiv");
  theMap.initialize();
});
Run Code Online (Sandbox Code Playgroud)

这是你想做的吗?

希望这可以帮助