2015-04-06 2 views
0

Я пишу плагин jQuery, который принимает в массив файлы json, которые затем мне нужно скомпилировать в один большой массив.

До сих пор разные части кода работали над собой, но как только я его собрал, я не могу вернуть новый массив.

Я предполагаю, что это либо мне не понять, как возвращать значения из вложенных циклов или вопрос о том, что $ .get() является Асинхронный и $ .each() петли синхронное. Или, вероятно, смесь обоих.

Я пробовал с jQuery $. Отдался, но не повезло. Любые указатели на то, как решить эту проблему, в основном приветствуются.

Вот код плагина на данный момент. Я комментировал код поэтому он должен быть 'легкий', чтобы увидеть то, что я пытаюсь сделать:

(function ($) { 
 
    
 
    $.fn.presspull = function(options) { 
 
    
 
     // This is the defaults settings which can be changed via the plugin call. 
 
     var settings = $.extend({ 
 
      // These are the defaults. 
 
      template \t : \t Handlebars.compile($('#pressTemplate').html()), 
 
      placeHolder : \t $("#press-grid"), 
 
      addMoreBtn \t : \t $("a#press-show-more"), 
 
      segment \t : \t 4, 
 
      dataSource \t : \t [] 
 
       
 
     }, options); // end settings 
 

 
     // non mutable elements which can not be changed from the plugin call. 
 
     var cache = { 
 
     \t \t pressArray \t : new Array(), 
 
     \t \t compileCount: 0, 
 
     \t \t segmentItt \t : 0 
 
     }; // end cache 
 

 
/*============================================================================ 
 
    – Compile Source: function to build and sort the combined press. 
 
==============================================================================*/ 
 

 
     function compileSource() { 
 
     \t // check if the data source contains anything. 
 
     \t if (settings.dataSource.length > 0) { 
 
     \t \t // for each json file in the data source do... 
 
\t   \t $.each(settings.dataSource , function(k, v) { 
 
\t   \t \t // get the data 
 
\t   \t \t $.get(v, function(data, status, xhr){ 
 
\t   \t \t \t // next loop through the output 
 
\t   \t \t \t $.each(data, function(i, e){ 
 
\t   \t \t \t \t // add each entry to the pressArray 
 
\t   \t \t \t \t cache.pressArray.push(e); 
 
\t   \t \t \t }); // end each 
 
\t   \t \t // once done do.. 
 
\t   \t \t }).done(function() { 
 
\t   \t \t \t // compile count increments for every data source 
 
\t \t \t \t \t \t cache.compileCount ++; 
 
\t \t \t \t \t \t if (cache.compileCount == settings.dataSource.length) { 
 

 
\t \t \t \t \t \t \t cache.pressArray.sort(function(a, b) { 
 
\t \t \t \t \t \t \t \t var c = new Date(a.date), 
 
\t \t \t \t \t \t \t \t \t d = new Date(b.date); 
 
\t \t \t \t \t 
 
\t \t \t \t \t \t \t \t return c>d ? -1 : c<d ? 1 : 0; 
 
\t \t \t \t \t \t \t }); // end sort 
 

 
\t \t \t \t \t \t \t // after compiling and sorting the new list we return it. 
 

 
\t \t \t \t \t \t }; // end if 
 
\t \t \t \t \t // if there is a failure in getting the data it's logged as following  \t \t \t 
 
\t   \t \t }).fail(function() { 
 
    \t \t \t \t \t console.log("Failed to get data from: " + v); 
 
    \t \t \t \t \t }); // end get.done 
 
\t   \t }); // end each 
 
     \t } else { 
 
     \t \t console.log("Source files not found!"); 
 
     \t }; 
 

 
     \t return console.log(cache.pressArray); 
 
     }; // end compileSource 
 

 
    
 
    }; // end $.fn.presspull 
 
    
 
}(jQuery));

The JSon файлов выглядит следующим образом:

[ 
 
     { 
 
      "publication": "Dazed & Confused", 
 
      "date": "2013-05-01", 
 
      "region": "UK", 
 
      "cover": "{{ 'img-press-cover-dazed-2013.png' | asset_url }}", 
 
      "pressmedia": [ 
 
        { 
 
        "name":"soma", 
 
        "image": "Document Name 1 - General", 
 
        "description": "description for image 1", 
 
        "keyproduct": "link to the key product on the image" 
 
        }, 
 
        { 
 
        "name":"soma2222", 
 
        "image": "Document Name 2 - General", 
 
        "description": "description for image 1", 
 
        "keyproduct": "link to the key product on the image" 
 
        } 
 

 
      ] 
 

 
]

И плагин называется следующим:

$().presspull({ 
 
     dataSource : [ 
 
     "http://link/to/external/json/file/01", 
 
     "http://link/to/external/json/file/02", 
 
     "http://link/to/external/json/file/03" 
 
     ] 
 
});

+2

Начнем с того, после 'функции compileSource()' функция и может добавить 'compileSource()'. Во-вторых, вы можете использовать ** callback **. – Turtle

+0

Вы можете «вернуть значение из' compileSource', поскольку оно асинхронно .... вам нужно использовать обратный вызов для обработки объединенного результата –

+0

@Turtle - спасибо за комментарий. Я думал, что использование .done() было обратным вызовом с использованием интерфейса Promise? –

ответ

1

Проблема здесь ваш метод compileSource является асинхронным, который означает, что при попытке вернуть массив из метода вы АЯКС содержимое не будет завершена, так что вы получите пустой массив.

Решение состоит в том, чтобы использовать функцию обратного вызова

function compileSource(callback) { 
     // check if the data source contains anything. 
     if (settings.dataSource.length > 0) { 
      // for each json file in the data source do... 
      $.each(settings.dataSource , function(k, v) { 
       // get the data 
       $.get(v, function(data, status, xhr){ 
        // next loop through the output 
        $.each(data, function(i, e){ 
         // add each entry to the pressArray 
         cache.pressArray.push(e); 
        }); // end each 
       // once done do.. 
       }).done(function() { 
        // compile count increments for every data source 
        cache.compileCount ++; 
        if (cache.compileCount == settings.dataSource.length) { 

         cache.pressArray.sort(function(a, b) { 
          var c = new Date(a.date), 
           d = new Date(b.date); 

          return c>d ? -1 : c<d ? 1 : 0; 
         }); // end sort 

         callback(cache.pressArray) 

         // after compiling and sorting the new list we return it. 

        }; // end if 
       // if there is a failure in getting the data it's logged as following    
       }).fail(function() { 
        console.log("Failed to get data from: " + v); 
       }); // end get.done 
      }); // end each 
     } else { 
      console.log("Source files not found!"); 
     }; 
    }; // end compileSource 

    //call the compile method 
    compileSource(function(array){ 
     //this function will be called once all the data is received and sorted, the sorted array will be passed as an argument 
    }) 
Смежные вопросы