Andrey Doronin Andrey Doronin - 2 months ago 7
jQuery Question

Refactor $(this) out of multiple click functions

I have the following simplified code:

$(".button1").click(function() {
var container = $(this).closest('.someClass');
container.doStuff();
specificFunction1();
});

$(".button2").click(function() {
var container = $(this).closest('.someClass');
container.doStuff();
specificFunction2();
specificFunction3();
});


Can I refactor out
$(this).closest('.someClass');
and make it a global variable so that
$(this)
always refers to the correct button?

Answer

I found a somewhat unexpected solution, that nevertheless reduces repetitive code so it works for me:

    $(".button1").click(function() {
          var container = getContainer($this);
          container.doStuff();
          specificFunction1();
        });

           $(".button2").click(function() {
          var container = getContainer($this);
          container.doStuff();
          specificFunction2();
          specificFunction3();
        });

   function getContainer(container){
    return container.closest('.someClass');
    }
Comments