Apparent javascript scope bug - help me out?

Status
Not open for further replies.
I am working on a thing that eats JSON and constructs a sequential gallery of images and videos. I am using jQuery. Here's the basic idea:

Code:
$.getJSON('http://my.awe/some/url/', '', function(data){
	var slides = data.slides;
	var curSlide = 0;

	/*** SNIPPED - some other gallery setup ***/
	
	function updateSlide(){
		slideStage.html('<img src='/html//civis/threads/+slides[curSlide].image+'>');
	}

	$('.nextSlide').live('click', function(){
		curSlide++;
		updateSlide();
		return false;
	});
	
	$('.prevSlide').live('click', function(){
		curSlide--;
		updateSlide();
		return false;
	});

	$('#close').live('click', hideGallery);
}

function hideGallery(){
	$('#slideshow').hide(800, function(){
		$(this).remove();
		$('#main-content').show();
        });
        return false;
}

So the narrative is, when I successfully get the JSON, I set up the gallery and allow people to click back and forth through the images/videos. Then when they're done, they click #close, which calls hideGallery and re-displays the main page content. My understanding is that .remove() in jQuery removes elements from the DOM as well as all EventListeners and other structures associated with them. So 'slides' should clear once the first $.getJSON goes out of scope. Then when the user clicks another gallery, $.getJSON should run again, 'slides' should be re-defined, and all should be well.

This was all working great on Friday, however today every time I call $.getJSON, my "slides" array continues to have the data from the first call in it. This is doubly weird because it's pulling the correct JSON from the server, and the first image of the "new" gallery loads fine. However, trying to click through the images doesn't work at all.

My understanding of Javascript scope is that every time $.getJSON succeeds, I should be allocating a new "slides" variable which contains the result of my JSON call. On Friday this is how it was working, however today it seems to have stopped. Is there something obvious here I am missing? Am I inadvertently creating a closure here? I haven't made significant changes to other sections of the code, so I am pretty stumped as to what changed over the weekend.

Thanks for taking a look!
 

technophile

Ars Legatus Legionis
23,768
Is there a reason you're not quoting the image source or otherwise generating valid HTML? Do the image URLs have spaces etc in them? Have you tried debugging using e.g. the Chrome live debugger to make sure the values are what you expect on the client side?

What is data.slides? Is it the json string or the rehydrated objects? (i.e. double check that it is what you think it is.)

More importantly, is there a reason you're not using e.g. shadowbox to do this rather than writing it yourself?
 
The image URL's are definitely valid (they are actually big long hashes, ie 8708703th09708035.jpg). Not quoting the tag's source is a good catch which I will fix, thank you. I have checked all my source data in jsonlint.org and it's all properly encoded and valid JSON - there's only 6 test galleries right now, so I can be pretty completist about checking existing data.

I have been going at it with both the Chrome debugger as well as Firebug, that's how I figured out that variable slides was funky. data.slides is rehydrated objects per the Chrome debugger. Upon the initial gallery load, 'slides' in the outer function matches perfectly with 'slides' in updateSlide, as expected. However, if I close the gallery and then reopen another one, when that one loads, at first they match, but then when I call updateSlides by clicking either "prev" or "next", slides inside updateSlide is somehow back to its previous value.

As far as why I'm not just using ColorBox or ShadowBox, partially because I want maximum possible control over the presentation to the user, and partially as a learning exercise :)

Additionally - I may have oversimplified the first post. The previous slide and next slide functions are actually:

Code:
 $('.nextSlide').live('click', function(){
                curSlide++;
                if(curSlide == slides.length){
                    curSlide = 0;
                    }
                updateSlide();
                return false;
            });

  $('.prevSlide').live('click', function(){
                curSlide--;
                if(curSlide < 0){
                    curSlide = (slides.length - 1);
                }
                updateSlide();
                return false;
            });

I thought maybe I am inadvertently creating a closure here, since I'm referencing 'slides' inside the click function, however even if I remove that line, the problem persists. Thanks for the help so far!
 

FromWork

Seniorius Lurkius
4
technophile":3hg2gf3p said:
Yeah, I think given that slides is a variable local to the completion function you are creating a closure. Try moving the declarations for both slides and curslide outside the function declaration and see if that helps. The initialization/assignment should still happen where it is, but the declaration needs to be global I think.

I don't think that's his issue (although the change may hide it). He is creating a closure, but the closure should be doing what he wants. I believe the problem is live() is registering multiple event handlers, one per AJAX call, all with different closure captures. Changing live() to bind() should fix that. I notice the code doesn't show where slideStage is declared/initialized, so hopefully there are no issues there.
 
Status
Not open for further replies.