我使用了一個框架(流星,但不要緊,我想這個問題),它提供了獨立的功能..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: '© <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替代品而不是使東西全球化?
編輯感謝您的回答,請問您可以添加一個代碼示例,例如使用您提到的模式之一,但基於我的代碼?這樣我可以更好地理解它。
你可能想看看這個其他可能類似的問題/答案(http://stackoverflow.com/questions/5063878/javascript-global-variables-best-practices?RQ = 1)。 – summea 2013-03-18 21:56:06
除了「命名空間」選項之外,您還可以對所有代碼(也稱爲模塊模式)使用單個閉包,以便變量可用於您的功能,而不是其他人。 – RobG 2013-03-18 22:29:28
[這篇文章](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth)很棒。 – jahroy 2013-03-19 02:51:48