Search code examples
jquerythisjquery-callback

How to pass context to method in a callback from event handler?


I've always written event handlers in jQuery like this:

$('.some-class').click(function() {
    alert('bla');
});

I learnt that would be better to avoid using anonymous functions in the callback, so I'm trying this way:

var function someMethod = function() {
    alert('bla');
};

$('.some-class').click(someMethod);

How can I pass a reference to the element I clicked on to someMethod?


Solution

  • Use this :

    var someMethod = function() {
      console.log(this); // => <button class="some-class">OK</button>
      console.log($(this).text()); // => OK
    };
    
    $('.some-class').click(someMethod);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button class="some-class">OK</button>