0

我有一个小函数用于处理 ajax 请求并从中获取数据。

一旦我的所有 JSON 被聚合到一个数组中,我就会触发一个事件。

我的问题是我的变量 mySources 是一个数组,在处理过程中被修改了。在事件触发之前,正如预期的那样,它是一个由 4 个数组组成的数组,但在被“监听”之后它只是一个数组(甚至不是一个数组中的一个数组,而只是第一个数组)

 function setSources(){
        var deffereds = [];

        if (arguments.length == 0)
            {
                deffereds.push(getTweets()),
                deffereds.push(getFacebookstatuses()),
                deffereds.push(getCampaigns()),
                deffereds.push(getArticles())
            }
            else
            {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] == 'tweet'){
                        deffereds.push(getTweets())
                    }
                    else if (arguments[i] == 'facebookstatus'){
                        deffereds.push(getFacebookstatuses())
                    }
                    else if (arguments[i] == 'campaign'){
                        deffereds.push(getCampaigns())
                    }
                    else if (arguments[i] == 'article'){
                        deffereds.push(getArticles())
                    }


                }
            }



            $.when.apply(null,deffereds).done(function(){ 

                var mySources = new Array();
                for (var i = 0; i < arguments.length; i++) {
                  mySources[i]=$.parseJSON(arguments[i][2].responseText).objects; 
                };
                console.log(mySources); **// This gives me an array of 4 arrays as expected**
                $(document).trigger('cal/results',mySources); 
            });

        $(document).on('cal/mySources', function(e,mySources){
            console.dir(mySources); **// This gives me only the first of the 4 arrays**
     });

 };
4

1 回答 1

0

将数组传递extraParameters给 时$.trigger,该数组是“未装箱”的,并且每个元素都作为单独的参数传递给事件处理程序。因此,您的事件处理程序实际上正在接收:

function(e, mySources0, mySources1, mySources2, ...) { }

一个简单的解决方案是在调用时将参数包装在另一个数组中trigger

$(document).trigger('cal/results', [mySources]); // Note the extra brackets

所以这应该是一个由四个数组组成的数组...... JavaScript 很有趣!

于 2013-07-09T18:53:11.687 回答