0

jQuery でスライドショーを実行し、「次のスライド」ボタンと「前のスライド」ボタンのコードを見て、いくつかの機能が変わることを除けば、ほとんど同じであることに気付きました。

これをリファクタリングしてより効率的にできると思いますが、どうすればよいかわかりません。

誰かが私に方法を教えてもらえますか?

//UI Binding
$nextbutton.on("click", function(){

    //Blocking control
    if (slideshowBlocked) return;
    slideshowBlocked = true;

    //Get active slide
    var $active = $slides.filter(".active");
    //Get new Slied
    var $newSlide = $active.next(".slide");
    if (!$newSlide.length){
        $newSlide = $slides.first();
    }

    //Prepare new slide beneath the active
    $newSlide.css({
        "z-index": 5,
        "display": "block"
    });

    //Fade out the active
    $active.fadeOut(function(){
        //Update states and CSS properties
        $(this).removeClass("active");
        $newSlide.addClass("active").css( "z-index", 10);;

        //Unblock slideshow
        slideshowBlocked = false;
    });
});
$prevbutton.on("click", function(){

    //Blocking control
    if (slideshowBlocked) return;
    slideshowBlocked = true;

    //Get active slide
    var $active = $slides.filter(".active");
    //Get new Slied
    var $newSlide = $active.prev(".slide");
    if (!$newSlide.length){
        $newSlide = $slides.last();
    }

    //Prepare new slide beneath the active
    $newSlide.css({
        "z-index": 5,
        "display": "block"
    });

    //Fade out the active
    $active.fadeOut(function(){
        //Update states and CSS properties
        $(this).removeClass("active");
        $newSlide.addClass("active").css( "z-index", 10);;

        //Unblock slideshow
        slideshowBlocked = false;
    });
});
4

3 に答える 3

1

あなたが言ったように、両方の関数が基本的に同じことをしていることを考えると、ファクトリ関数を使用して、必要なオプションを渡すだけです。文字列に基づくロジックは必要ありません。適切な関数名を使用するだけです。

function slide (direction, fallback) {
    return function () {
        //Blocking control
        if (slideshowBlocked) return;
        slideshowBlocked = true;

        //Get active slide
        var $active = $slides.filter(".active");

        //Get new slide
        var $newSlide = $active[direction](".slide");
        if (!$newSlide.length) {
            $newSlide = $slides[fallback]();
        }

        //Prepare new slide beneath the active
        $newSlide.css({
            "z-index": 5,
            "display": "block"
        });

        //Fade out the active
        $active.fadeOut(function(){
            //Update states and CSS properties
            $(this).removeClass("active");
            $newSlide.addClass("active").css( "z-index", 10);

            //Unblock slideshow
            slideshowBlocked = false;
        });
    }
}

$nextbutton.on('click', slide('next', 'first'));
$prevbutton.on('click', slide('prev', 'last'));
于 2013-04-16T10:17:23.407 に答える