繁体   English   中英

将值分配给JavaScript中的全局变量列表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM