0

I have used keyup to bind an input element to a function text_1. The function somehow gets the value of the text field by $(this).val().

I tried to understand this, but the best explanation is "this always refers to the “owner” of the function we're executing". What is the "owner" in this case? How does $(this).val() become the value of the field? What gets passed when keyup occurs?

I am a newb in Javascript and jQuery.

   function text_1() {
     var val = $(this).val(),
       html = 'Not-debounced AJAX request executed: ' + text_counter_1++ + ' times.'
       + ( val ? ' Text: ' + val : '' );

     $('#text-type-1').html( html );
   };

   $('input.text').keyup( text_1 );
Jesvin Jose
  • 20,780
  • 25
  • 95
  • 183
  • possible duplicate of [JavaScript "this" keyword](http://stackoverflow.com/questions/3127429/javascript-this-keyword) – undefined Feb 18 '14 at 15:26

1 Answers1

2

"this" is set based on the current context and scope. JQuery will set "this" to the element triggering the event. In this case JQuery will set "this" to point to the html element (input) that is firing the key up event.

By doing $(this) - you are wrapping the html element, currently set to this, with a JQuery object and thus you can call .val() on your search input.

Newse
  • 2,290
  • 1
  • 10
  • 7
  • What exactly does `keyup` do with the function then? – Jesvin Jose Feb 18 '14 at 15:33
  • 1
    @aitchnyu it uses .call or .apply on it, with the element and the normalized event object as parameters. `yourfunction.call(theelement,eventObject)` – Kevin B Feb 18 '14 at 15:33
  • @aitchnyu - key up takes a function pointer to your event handler. When the event is triggered it calls your function and sets the context appropriately. – Newse Feb 18 '14 at 15:34
  • @KevinB - good point. Call/Apply are used to set the context – Newse Feb 18 '14 at 15:36
  • Must get used to the fact that jQuery uses declarative stuff and higher order functions a lot. – Jesvin Jose Feb 18 '14 at 15:45