0

I have the following code:

// star/un-star
$('.starred').on("click", function(event) {
    var inp = $(this)
    var user_id = $(this).data('user_id');
    var current_value = $(this).data('value');
    var new_value = current_value == '0' ? 1 : 0;
    $.post('/update_starred/', {'user_id': user_id, 'new_value': new_value}, function (response) {
        inp.addClass('new')

    });
});

I have noticed that I have to define var inp = $(this) if I am to use that value within the post function. Why doesn't it keept the $(this) value there? What is the value for $(this) within the post function? Why?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 3
    In an event listener, `this` refers to the EventTarget that the event was bound to. The `$.post` callback may have its own `this`. – Sebastian Simon Aug 03 '18 at 22:06
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Sebastian Simon Aug 03 '18 at 22:06
  • Because the code is calling a function on that object: `inp.addClass('new')` So it needs a reference to that object. Since it's happening in an asynchronous operation, the context of `this` is lost by then. So it stores it in a variable first. – David Aug 03 '18 at 22:06
  • 3
    By the way, as long as you've already defined `var inp = $(this)`, you should get rid of the other occurrences of `$(this)` and use `inp` there instead. No sense turning `this` into a new jQuery object over and over again. – kshetline Aug 03 '18 at 22:10
  • From my experience I would say someone did the first part of code with $this due not caring enough. After that he added functionality that needed post, and since this is set to different value there he made the variable, yet once again didn’t care enough to replace all occurrence of it to the variable. – Akxe Aug 03 '18 at 22:10
  • I wrote a long wrong answer thinking you were asking about the listener API. XMLHttpRequest's callback is executed with this referring to the XMLHttpRequest itself. That's why you have to either pass inp instead of $(this) or use a bound function. – ibrahim tanyalcin Aug 03 '18 at 22:20

0 Answers0