[LRUG] Intermittent jQuery Problem

Andrew Stewart boss at airbladesoftware.com
Tue Oct 27 09:40:46 PDT 2009


Hello Abhishek,

>  I suspect you might have a scoping problem, Sometimes you might see  
> a weird behavior of eventhandler calls when you try to access the  
> data referenced out of its scope.

Ok, that sounds plausible.

> Where is sample_id ?, in which scope?

Sorry...in trying to pare down that code to the bare essentials, I  
omitted a bit too much.  Here's the full code:

   $('#samples .results a.add').livequery('click', function(event) {
     event.preventDefault();
     var story_id  = $ 
(this).parents('.check_out').attr('id').split('_')[1];
     var sample    = $(this).parents('tr');
     var sample_id = sample.attr('id').split('_')[1];
     var loans_url = '/stories/' + story_id + '/loans';

     // AJAX to add the sample to the story.
     $.ajax({
       type:       "POST",
       url:        loans_url,
       data:       {'loan[sample_id]':sample_id},
       beforeSend: function()     { sample.remove(); },
       success:    function(data) { $('#basket table  
tr:last').after(data); }
     });
   });

Is that a good scope for sample_id?

> You might want to try something with scoping, like this...
>
>  $('#samples .results a.add').livequery('click', function(event) {
>
>    event.preventDefault();
>
>    var your_sample_id_goodness =  
> sample_id_that_comes_from_well_bound_scope;
>
>    return function(){
>       // AJAX to add the sample to the story.
>       $.ajax({
>         type:       "POST",
>         url:        '/stories/2716/loans',
>         data:       {'loan[sample_id]': your_sample_id_goodness,
>         beforeSend: function()     { sample.remove(); },
>         success:    function(data) { $('#basket table  
> tr:last').after(data); }
>       });
>      }(); //End of return
>
>   });

What effect does wrapping a function around the AJAX call have?  I  
can't see how it would help ;)

Thanks,

Andy
-----
http://airbladesoftware.com



More information about the Chat mailing list