[英]Assigning values to a list of global variables in JavaScript
嘿,現在我正在使用jQuery,並且我有一些全局變量來保存一些預加載的ajax東西(預加載以使頁面顯示得很好且快速):
$.get("content.py?pageName=viewer", function(data)
{viewer = data;});
$.get("content.py?pageName=artists", function(data)
{artists = data;});
$.get("content.py?pageName=instores", function(data)
{instores = data;});
$.get("content.py?pageName=specs", function(data)
{specs = data;});
$.get("content.py?pageName=about", function(data)
{about = data;});
如您所見,我們嚴重違反了DRY原則,但是...我真的沒有找到解決它的方法...有什么想法嗎?
也許是數組?
使用jQuery每個方法來遍歷頁面名稱數組,然后設置全局(在窗口范圍內)變量:
jQuery.each(
["viewer", "artists", "instores", "specs", "about"],
function (page) {
$.get("content.py?pageName=" + page,
new Function("window[" + page + "] = arguments[0]"));
}
);
更新:實際上,您甚至不需要“新功能”:
jQuery.each(
["viewer", "artists", "instores", "specs", "about"],
function (page) {
$.get("content.py?pageName=" + page, function () { window[page] = arguments[0]; });
}
);
您不需要eval()
或Function()
。 您懷疑,數組可以很好地完成此工作:
(function() // keep outer scope clean
{
// pages to load. Each name is used both for the request and the name
// of the property to store the result in (so keep them valid identifiers
// unless you want to use window['my funky page'] to retrieve them)
var pages = ['viewer', 'artists', 'instores', 'specs', 'about'];
for (var i=0; i<pages.length; ++i)
{
// "this" refers to the outer scope; likely the window object.
// And will result in page contents being stored in global variables
// with the same names as the pages being loaded. We use the with({})
// construct to create a local scope for each callback with the
// appropriate context and page name.
with ({context: this, pageName: pages[i]})
$.get("content.py?pageName=" + pageName, function(data)
{context[pageName] = data;});
}
})(); // close scope, execute anonymous function
// at this point, viewer, artists, etc. are populated with page contents
// (assuming all requests completed successfully)
您可以使用新功能避免評估:
var names = ['viewer', 'artists', 'instores', 'specs', 'about'];
for (var i = 0; i < names.length; i++)
$.get("content.py?pageName=" + names[i], new Function('data', names[i] + ' = data;'));
雖然還沒好很多
您只能在該頁面上調用一次,並返回一個json對象而不是文本
{
viewer:'me',
artists:'you',
instores:'instores',
specs:'specs',
about:'about'
}
並估計,既然您現在要給服務器撥打N次電話,這會減慢所有速度,您應該重新考慮自己的邏輯!
PS。 正如我寫的那樣,我看到了RoBorg的答案,您會看到,在使用新功能時,您正在幕后使用eval,因此,如果要使用它,那就去吧(在某些瀏覽器中也更快)
盡管使用起來比較羅word,但這並沒有使用eval。
function get_content(name){
$.get("content.py?pageName=" + name, function(data){ window[name] = data;});
}
var names = ['viewer', 'artists', 'instores', 'specs', 'about'];
for (var i = 0; i < names.length; i++)
get_content(names[i]);
但是其中一位答卷者提出了一個很好的建議,您應該嘗試將所有這些請求合並為一個,否則您的服務器將被點擊6次,以獲取頁面上每個請求的動態內容。
這些建議的解決方案大多數都避免使用eval 。 這種做法在Doduglas Crockford的“ JavaScript編程語言代碼約定”中得到了進一步加強,其中部分內容是
“評估是邪惡的
eval函數是JavaScript中最常被濫用的功能。 躲開它。
eval有別名。 不要使用Function構造函數。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.