views:

140

answers:

1

Hi all I am not sure how to approach this problem. I have a function that is passed an array of HTML img elements. It loops through these images checking the SRC attribute for images using a blank "no image" thumb nail. It then executes an image search using the img tags ALT attribute as the query. The callback function on the search then replaces the Img SRC with the first image result.

I am having problems matching up the correct image with the corresponding search callback. Right now I am just creating arrays and matching the returned search with an index for the images. Since the multiple searches run concurrently, depending on the size of the image or network latency they can fire the call back out of order and mix up the images.

I need an approach that lets me pair individual searches with html elements. Would this be possible using a searchController and multiple imageSearch objects?

Below is an example of the function I am using

google.load('search', '1');

function googleFillBlanks(jqueryImages){

  //namePairs holds the images matching alt text and attachedCount is used for matching up once the call back is fired
  var attachedCount = 0;
  var namePairs = [];

  function searchComplete(searcher){
    if (searcher.results && searcher.results.length > 0) {
       var results = searcher.results;
       var result = results[0];
       $("img[alt='"+namePairs[attachedCount]+"'] ").attr('src', result.tbUrl);
       //jqueryImages.get(0).attr('src', result.tbUrl);
       attachedCount++;
    }
  }

   var imageSearch = new google.search.ImageSearch();

    //restrict image size
    imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                               google.search.ImageSearch.IMAGESIZE_SMALL);

    imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);

  jqueryImages.each(function(){
    if($(this).attr('src').substr(-12,8) == 'no_image')
    { 
      namePairs.push($(this).attr('alt'));
      imageSearch.execute($(this).attr('alt'));
    }
  });
}
A: 

this is what I ended up doing encase any one is interested and for self reminder

google.load('search','1');
function checkImages(){

 // Here is the closure!
 var myClosure = function(img){return function(){
  if(this.results&&this.results.length>0){
   var result = this.results[0];
   img.src = result.tbUrl;
   img.alt = result.titleNoFormatting;
  }
 }};

 var imgs = document.getElementsByTagName('img');
 for(var i=0;i<imgs.length;i++){
  var img=imgs[i];
  if(img.src.match(/no_image.{4}/)){
   var is = new google.search.ImageSearch();
   is.setSearchCompleteCallback(is, myClosure(img));
   is.execute(img.alt);
  }
 }
}
google.setOnLoadCallback(checkImages);
kevzettler