JavaScript Globals替代品

时间:2013-03-18 21:53:00

标签: javascript oop global-variables closures

我正在使用一个框架(流星,但对于我猜的问题无关紧要),它提供了单独的功能。

我的问题是我意识到我正在使用越来越多的全局变量,以便在这些函数之间访问它们。例如地图对象:

Meteor.startup(function () {
  map = L.map('map_canvas').locate({setView: true, maxZoom: 21});
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);
});

我需要访问地图到处操作我的地图(使用Leaflet) 例如:

Template.messages.events({
  'click .delete-message': function (e,t) {
    e.stopPropagation();
    removeItem(e.target.id);
  },
  'click .message': function (e,t) {
    console.log('event clicked');
    map.setView([e.target.getAttribute('data-lat'),e.target.getAttribute('data-lng')], 16);
  }
});

当我想创建一个我想在不同地方使用的标记对象时,我遇到同样的问题...

Meteor是以这种方式构建的,还是有更多适当/干净的JS替代品,而不是让全球化的东西?

编辑感谢您的回答,是否可以使用您提到的其中一种模式但根据我的代码添加代码示例?这样我就能更好地理解它。

1 个答案:

答案 0 :(得分:1)

有很多方法可以使js变量和函数不是全局的。

  1. 您可以使用对象作为哈希映射,并使用点表示法访问您的变量。该对象仍然是全局的,但至少可以冲突的全局名称更少。
  2. 您可以使用 namespace.js
  3. 您可以使用 pseudo-oo style using closures
  4. 您可以使用 coffeescript
  5. 除了namespace.js之外,很多像 dojo.js 这样的框架都允许使用模块。
  6. 可能还有很多其他选择。
  7. Dojo.js和我认为require.js鼓励模块化设计。 (其中包括)Namespace很容易包含和使用,并且可以用最少量的代码更改来解决您的问题。我过去曾用它来从全球化到更多OO风格。

    选项1,Hashmap

    var GKApp = new Object();
    GKApp.map = blah;
    GKApp.size = 1;
    GKApp.doSomethingWithMap = function() {
        GKApp.map.blah();
    }
    // Now the only global is GKApp.
    // Later, make the call. 
    GKApp.doSomethingWithMap.call();
    

    选项3,闭包

    您可以使用如下所示的纯javascript闭包,或使用dojo.js或require.js将其包装在define中。

    GKApp = function(pmap) {
        // dbg.log("GKApp constructor.");
        // You can consider the closure to 'begin' here.
    
        // ********************************************************
        // @private variables:
        // ********************************************************
        var map = pmap;
    
        /**
         * @privileged method which has access to variables in the closure.
         * These variables are not available outside of the closure.
         * An anonymous function has access to variables in the outer scope or, the closure.
         */
        this.doSomethingWithMap = function() {
            map.blah();
        };
    };
    
    // Later, instantiate an object and use it. 
    var gkApp = new GKApp(map);
    gkApp.doSomethingWithMap();
    
相关问题