jQuery插件数据与多个实例混合

时间:2012-02-14 17:28:45

标签: javascript jquery jquery-plugins

我正在尝试开发一个jQuery插件来显示自适应图像库。我正在使用.data()来存储图库每张幻灯片的信息。

在显示单个图库时,所有内容似乎都正常工作,但在尝试在单个页面上设置多个图库实例时会混淆。 A rough demo can be viewed here

以下是正在运行的代码:

(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');
});

在表面上,它似乎创建了两个具有适当幻灯片结构的画廊:

  • 库2
    • 库2-滑动-0
    • 库2-滑动-1
    • 库2-滑动-2
    • 库2-滑动-3
    • 库2-滑动-4
    • 库2-滑动-5
  • gallery3
    • gallery3滑动-0
    • gallery3滑动-1

但是,onclick操作不适用于Gallery2的最后两张幻灯片(两个库中复制的幻灯片)。仔细检查DOM后,我可以看到存储在gallery2数据中的幻灯片有以下ID:

  • 库2
    • 库2-滑动-0
    • 库2-滑动-1
    • 库2-滑动-2
    • 库2-滑动-3
    • gallery3滑动-0
    • gallery3滑动-1

我不确定导致混淆或如何修复的原因,所以任何帮助都会非常感激。 感谢

1 个答案:

答案 0 :(得分:0)

您的问题是调用$('.pGallery').gallery('addItems'...会导致将相同的对象添加到两个库的内部结构中,当您调用$('.pGallery').gallery('updateCarousel');时,将覆盖存储在这些对象中的ID。

您需要在其中放置原始对象的副本。做:

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]));
    };
},

使用jQuery.extend({}, oldObject),您可以执行shallow copy;