简体   繁体   中英

jQuery Object Literal Pattern

In an effort to write cleaner code i have decided to learn some design patterns. I really love the Object Literal Module pattern, but im having a bit of trouble. I have created a lightbox in spaghetti code and have not been able to convert it to a object literal pattern.

var $overlay = $("<div class='lightbox'></div>");
var $img = $("<img>");
var $caption = $("<p class='caption'></p>");



$overlay
    .append($img)
    .append($caption);



$('body').append($overlay);


$('.gallery li').click(function (e) {
    e.preventDefault();

    var src = $(this).children('img').attr("src");
    var cap = $(this).children('img').attr("alt");

    $img.attr('src',src);
    $caption.text(cap);

    $overlay.fadeIn('fast');

    $overlay.click(function () {
        $overlay.fadeOut('fast');
    });
});

I've refactored the code into an object literal using the same kind of structure you linked with your post. All created elements are in the lightbox.el namespace and you initiate the lightbox with lightbox.init() .

var lightbox = {
    el: {
        overlay: $("<div class='lightbox'></div>"),
        img: $("<img>"),
        caption: $("<p class='caption'></p>"),
        galleryItems: $('.gallery li'),
        body: $('body')
    },
    fadeSpeed: 'fast',
    init: function(){
        lightbox.append();
        lightbox.bindUIActions();
    },
    bindUIActions: function(){
        lightbox.el.galleryItems.click(lightbox.handleGalleryClick);
    },
    handleGalleryClick: function(e){
        e.preventDefault();
        var src = $(this).children('img').attr("src");
        var cap = $(this).children('img').attr("alt");

        lightbox.el.img.attr('src',src);
        lightbox.el.caption.text(cap);    
        lightbox.el.overlay.fadeIn(lightbox.fadeSpeed);    
        lightbox.el.overlay.click(lightbox.fadeOutOverlay);
    },
    fadeOutOverlay: function(){
        lightbox.el.overlay.fadeOut(lightbox.fadeSpeed);
    },
    append: function(){
        lightbox.el.overlay
            .append(lightbox.el.img)
            .append(lightbox.el.caption);
        lightbox.el.body.append(lightbox.el.overlay);
    }
}

Usage:

lightbox.init();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM