Search code examples
javascriptjqueryreusability

Code reuse with different event methods


I have two similar pieces of code in two different functions of my project and I want to get rid of the repeating code. How can I do that?

1:

getArray("my-hand").forEach(function(elem){
    $(elem).mouseover(function(){
        $(this).css({'top': '1em'});
    });
    $(elem).mouseout(function(){
        $(this).css({'top': '0em'});
    });
    $(elem).click(function(){   
        var cardNode = $(this).get(0);
        //some jquery animation
        play(cardNode,time);
    });
})

and the second piece

2:

getArray("my-hand").forEach(function(elem){
    $(elem).mouseover(function(){
        $(this).css({'top': '1em'});
    });
    $(elem).mouseout(function(){
        $(this).css({'top': '0em'});
    });
    $(elem).click(function(){   
        var cardNode = $(this).get(0);
        //a function with another jquery animation
        validateCardAndAddForCollection(checkNumber,cardNode,time);
    });
})

Solution

  • One way is to put it in a function, and pass as an argument to that function a callback that will execute the desired code:

    function handleCards (cb) {
        getArray("my-hand").forEach(function(elem){
            $(elem).mouseover(function(){
                $(this).css({'top': '1em'});
            });
            $(elem).mouseout(function(){
                $(this).css({'top': '0em'});
            });
            $(elem).click(function(){   
                var cardNode = $(this).get(0);
                //some jquery animation
    
                cb(cardNode);
            });
        });
    }
    
    handleCards(function (cardNode) {
        play(cardNode, time);
    });
    
    handleCards(function (cardNode) {
        validateCardAndAddForCollection(checkNumber,cardNode,time);
    });