Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue maintaining scope with jQuery / module pattern

I'm just starting out using module patterns (thanks to Christian Heilmann's original tutorial) to organize my jQuery and I'm running into a weird issue. Consider the following javascript code:

var Gallery = function(){

  var $obj, $thumbs, $mainPic;

  function init($e){

    $obj = $e;
    $thumbs = $obj.find('.thumbnail');
    $mainPic = $obj.find('.main-pic');

    $obj.find($thumbs).bind('click',updateMainPic);

  };

  function updateMainPic() {
    $thumbs.removeClass('selected');
    $thumb = $thumbs.filter(this);
    $thumb.addClass('selected');
    newPicUrl = $thumb.data('src');    
    $mainPic.attr('src',newPicUrl);    
  };

  return {
    init:init
  }

}();

Which is included and used on the follow HTML:

<div id="gallery1">
  <img src="" class="main-pic">
  <ul>
    <li class="thumbnail" data-src="photo1.jpg">Photo 1</li>
    <li class="thumbnail" data-src="photo2.jpg">Photo 2</li>
    <li class="thumbnail" data-src="photo3.jpg">Photo 3</li>
    <li class="thumbnail" data-src="photo4.jpg">Photo 4</li>
  </ul>
</div>
<script type="text/javascript">
  Gallery.init($('#gallery1'));
</script>

<div id="gallery2">
  <img src="" class="main-pic">
  <ul>
    <li class="thumbnail" data-src="photo1.jpg">Photo 1</li>
    <li class="thumbnail" data-src="photo2.jpg">Photo 2</li>
    <li class="thumbnail" data-src="photo3.jpg">Photo 3</li>
    <li class="thumbnail" data-src="photo4.jpg">Photo 4</li>
  </ul>
</div>
<script type="text/javascript">
  Gallery.init($('#gallery2'));
</script>

The problem I'm running into is that clicking the thumbnails on #gallery1 is swapping the image of #gallery2, yet #gallery2 is working as expected. It would seem the the $obj variable is being shared across the instances, but I thought it remained scoped to the private instance of the function.

Any advice on how to get this properly scoped and working would be greatly appreciated.

like image 321
bjork24 Avatar asked Jun 05 '26 05:06

bjork24


1 Answers

Problem is that Gallery is a singleton. The moment you call the second init, you're replacing the internal $obj variable.

I wouldn't use a module pattern in this situation. If you're using jQuery anyway, it'd be easier to write a jQuery plugin (simple) or a jQuery UI Widget (is really good at maintaining state).

like image 152
Mike Robinson Avatar answered Jun 06 '26 18:06

Mike Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!