2

I'm trying to develop a jQuery plugin to display adaptive image galleries. I'm using .data() to store the information for each slide of the gallery.

Everything appears to be working okay when displaying a single gallery, but gets mixed up when trying to have multiple gallery instances on a single page. A rough demo can be viewed here.

Here is the code that is being run:

(function($) {
    $.Gallery = function(element, options) {
        this.$el = $(element);
        this._init(options);
    };

    $.Gallery.defaults = {
        showCarousel : true,
    };

    $.Gallery.prototype = {
        _init : function(options) {
            var $this = $(this);
            var instance = this;

            // Get settings from stored instance
            var settings = $this.data('settings');
            var slides = $this.data('slides');

            // Create or update the settings of the current gallery instance
            if (typeof(settings) == 'undefined') {
                settings = $.extend(true, {}, $.Gallery.defaults, options);
            }
            else {
                settings = $.extend(true, {}, settings, options);
            }
            $this.data('settings', settings);

            if (typeof(slides) === 'undefined') {
                slides = [];
            }
            $this.data('slides', slides);

            instance.updateCarousel();
        },

        addItems : function(newItems) {
            var $this = $(this),
                slides = $this.data('slides');

            for (var i=0; i<newItems.length; i++) {
                slides.push(newItems[i]);
            };
        },

        updateCarousel : function() {
            var instance = this,
                $this = $(this);
                slides = $(instance).data('slides');

            var gallery = instance.$el.attr('id');

            /* Create carousel if it doesn't exist */
            if (instance.$el.children('.carousel').length == 0) {
                $('<div class="carousel"><ul></ul></div>').appendTo(instance.$el);
                var image = instance.$el.find('img');
            };

            var carouselList = instance.$el.find('.carousel > ul'),
                slideCount = slides.length,
                displayCount = carouselList.find('li').length;


            if (displayCount < slideCount) {
                for (var i=displayCount; i<slides.length; i++) {                    
                    slides[i].id = gallery + '-slide-' + i;
                    slide = $('<img>').attr({src : slides[i].thumb}).appendTo(carouselList).wrap(function() {
                        return '<li id="' + slides[i].id + '" />'
                    });

                    slide.on({
                        click : function() {
                            instance.slideTo($(this).parent().attr('id'));
                        },
                    });
                };
            };
        },

        slideTo : function(slideID) {
            var $this = $(this);
            var slides = $this.data('slides');
            var image;
            var $instance = $(this.$el);

            $(slides).each( function() {
                if (this.id == slideID){
                    image = this.img;
                };
            });

            $('<img/>').load( function() {
                $instance.find('div.image').empty().append('<img src="' + image + '"/>');
            }).attr( 'src', image );
        },
    };

    $.fn.gallery = function(options) {

        args = Array.prototype.slice.call(arguments, 1);

        this.each(function() {
            var instance = $(this).data('gallery');

            if (typeof(options) === 'string') {
                if (!instance) {
                    console.error('Methods cannot be called until jquery.responsiveGallery has been initialized.');
                }
                else if (!$.isFunction(instance[options])) {
                    console.error('The method "' + options + '" does not exist in jquery.responsiveGallery.');
                }
                else {
                    instance[options].apply(instance, args);
                }
            }
            else {
                 if (!instance) {
                    $(this).data('gallery', new $.Gallery(this, options));
                }
            }
        });
        return this;
    };

})(jQuery);

$(window).load(function() {
    $('#gallery2').gallery();
    $('#gallery3').gallery();

    $('#gallery2').gallery('addItems', [
        {
            img: 'images/image2.jpg',
            thumb: 'images/image2_thumb.jpg',
            desc: 'Image of number 2'
        },
        {
            img: 'images/image3.jpg',
            thumb: 'images/image3_thumb.jpg',
            desc: 'Image of number 3'
        },
        {
            img: 'images/image4.jpg',
            thumb: 'images/image4_thumb.jpg',
            desc: 'Image of number 4'
        },
        {
            img: 'images/image5.jpg',
            thumb: 'images/image5_thumb.jpg',
            desc: 'Image of number 5'
        }
    ]);

    $('.pGallery').gallery('addItems', [
        {
            img: 'images/2.jpg',
            thumb: 'images/2_thumb.jpg',
            desc: 'Image of number 0'
        },
        {
            img: 'images/image1.jpg',
            thumb: 'images/image1_thumb.jpg',
            desc: 'The second image'
        }
    ]);
    $('.pGallery').gallery('updateCarousel');
});

On the surface it appears to create two galleries with the proper slide structure of:

  • gallery2
    • gallery2-slide-0
    • gallery2-slide-1
    • gallery2-slide-2
    • gallery2-slide-3
    • gallery2-slide-4
    • gallery2-slide-5
  • gallery3
    • gallery3-slide-0
    • gallery3-slide-1

However, the onclick action doesn't work for the last two slides of Gallery2 (the slides duplicated in both galleries). Upon closer inspection of the DOM, I can see that the slides stored in data for gallery2, have the following ids:

  • gallery2
    • gallery2-slide-0
    • gallery2-slide-1
    • gallery2-slide-2
    • gallery2-slide-3
    • gallery3-slide-0
    • gallery3-slide-1

I'm not sure what is causing the mix-up or how to fix, so any help would be greatly appreciated. Thanks

raptureaid
  • 23
  • 4
  • I think you're complicating things too much. Why don't you try a simpler approach? – elclanrs Feb 14 '12 at 18:02
  • @elclanrs - Not sure what you are referring to as complicated. A simplified explanation of the use case is: have multiple instances of a plugin on a page, use $.data() to store data unique to each instance, get unique data from each instance's $.data() storage. At some point in the example code, unique data from one instance is getting pulled into the other instance. I would like to know why this is happening and how it can be corrected in the context of the use case. – raptureaid Feb 14 '12 at 18:53

1 Answers1

0

Your problem is that calling $('.pGallery').gallery('addItems'... cause the same objects to be added to the internal structure of both galleries, when you call $('.pGallery').gallery('updateCarousel'); the ids stored in those objects are overwritten.

You need to put a copy of the original objects in there. Do:

addItems : function(newItems) {
    var $this = $(this),
        slides = $this.data('slides');

    for (var i=0; i<newItems.length; i++) {
        //slides.push(newItems[i]);
        slides.push(jQuery.extend({}, newItems[i]));
    };
},

With jQuery.extend({}, oldObject) you can perform a shallow copy;

Community
  • 1
  • 1
Prusse
  • 4,287
  • 2
  • 24
  • 29