2013-03-18 71 views
1

我使用了一個框架(流星,但不要緊,我想這個問題),它提供了獨立的功能..JavaScript的全局替代

我的問題是我意識到我正在使用越來越多的全局變量以使它們在這些功能之間可訪問。例如,地圖對象:

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); 
}); 

我需要訪問地圖無處不在操縱我的地圖(使用單張的) 例如:

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); 
    } 
}); 

我有同樣的問題當我想要創建一個標記對象,我想在不同的地方使用...

流星是以這種方式建造,還是有更合適/乾淨的JS a替代品而不是使東西全球化?

編輯感謝您的回答,請問您可以添加一個代碼示例,例如使用您提到的模式之一,但基於我的代碼?這樣我可以更好地理解它。

+1

你可能想看看這個其他可能類似的問題/答案(http://stackoverflow.com/questions/5063878/javascript-global-variables-best-practices?RQ = 1)。 – summea 2013-03-18 21:56:06

+1

除了「命名空間」選項之外,您還可以對所有代碼(也稱爲模塊模式)使用單個閉包,以便變量可用於您的功能,而不是其他人。 – RobG 2013-03-18 22:29:28

+1

[這篇文章](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth)很棒。 – jahroy 2013-03-19 02:51:48

回答

1

有許多方法可以使js變量和功能不是全局的。

  1. 您可以使用對象作爲哈希映射,並用點符號訪問您的變量。該對象仍然是全球性的,但至少有少數全球名稱可能會發生衝突。
  2. 您可以使用namespace.js
  3. 您可以使用pseudo-oo style using closures。您可以使用coffeescript
  4. 除了namespace.js,許多框架如dojo.js允許模塊。
  5. 也許很多其他選項。

Dojo.js和我認爲require.js鼓勵模塊化設計。 (其中包括)名稱空間非常容易包含和使用,並且可以通過最少量的代碼更改來解決您的問題。我過去使用它從全球變爲更多OO風格。

選項1,哈希映射

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閉合如下所示或在define使用的dojo.js包裝這個或要求。 JS。

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(); 
+0

這比這還多一點。例如,散列意味着在不使用單詞「散列」來表示關聯數組的語言環境中的其他內容。它意味着一個可以用作數據標識符的計算值。例如MD5和CRC32就是哈希的例子。另一方面,實際上調用一個對象也是爲了教育新手程序員關於js中對象的動態性質。 – slebetman 2013-03-19 05:46:06

+1

傑西蒙感謝您的詳細解答。之前我已經閱讀過關於模塊化設計和閉包的內容,但現在我實際上試圖實現我有更實際的問題:首先想到的是,閉包應該限制變量的範圍。到現在爲止還挺好。但我所問的是如何在不污染全局範圍的情況下安全地共享不同功能之間的變量。我猜想使用模塊化模式會有幫助 - 整個要點是使用「返回」 - 或者我錯了? – 2013-03-19 17:31:15

+0

我有地圖對象 - 這基本上是我的主要問題,因爲我想在不同的功能中訪問它。 – 2013-03-19 18:47:25