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

Jia*_*aro 1 javascript jquery dry

嘿,现在我正在使用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;});
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我们严重违反DRY原则,但是......我真的没有办法解决这个问题......任何想法?

也许是阵列?

Ate*_*ral 6

使用jQuery每个方法迭代一个页面名称数组,然后设置一个全局(在窗口范围内)变量:

jQuery.each(
    ["viewer", "artists", "instores", "specs", "about"],
    function (page) {
        $.get("content.py?pageName=" + page,
            new Function("window[" + page + "] = arguments[0]"));
    }
);
Run Code Online (Sandbox Code Playgroud)

更新:实际上,你甚至不需要"新功能":

jQuery.each(
    ["viewer", "artists", "instores", "specs", "about"],
    function (page) {
        $.get("content.py?pageName=" + page, function () { window[page] = arguments[0]; });
    }
);
Run Code Online (Sandbox Code Playgroud)


Sho*_*og9 5

你不需要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)
Run Code Online (Sandbox Code Playgroud)