Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What context is the jQuery.post callback function invoked in?

Lets say for example:

$(".button").click(function() {

    $.post("commandrunner.php",
        {
            param1: 'value',
            param2: 'value2',
            param3: 'value3'
        },
        function(data, textStatus) {
            $(this).parent().after('<p>button clicked</p>');
        },
        "json"
    );

});

I ran this and it didn't work. I tried a couple of things before I theorized the callback wasn't being invoked in the context of this particular ".button" and so $(this) was useless. This worked instead:

$(".button").click(function() {
    var thisButton = $(this);

    $.post("commandrunner.php",
        {
            param1: 'value',
            param2: 'value2',
            param3: 'value3'
        },
        function(data, textStatus) {
            thisButton.parent().after('<p>button clicked</p>')
        },
        "json"
    );

});

This feels like a bit of a hack. Is this the right way to get a reference to the clicked on button? And what context is that (or any other callback) invoked in?

Thanks!

Ali

like image 530
Ali Avatar asked Jun 30 '09 15:06

Ali


2 Answers

What you've noticed here is the way JavaScript closures work. As in other OO languages, when a method is invoked, it has a "this", which is similar to Java's this or Ruby's self. However, the JavaScript this is remarkably malleable, and jQuery takes advantage of that property to set it to a useful value when it calls your callback.

In the case of events, jQuery sets the this pointer to point at the element that you bound the event handler to. Check this out:

var hello = function() {
  console.log("Hello " + this);
});

If you come from an OO background, you might look at the above snippet in bewilderment: what does this point to. By default, it will point at the global object (window in browsers). But you can easily override that:

hello.call("world") // will print "Hello world"

Call takes multiple arguments after the this which are passed in as arguments. A similar method, called apply, will also take a this as the first argument, but takes an Array of arguments as the second parameter.

Now, if we look at your example again:

$(".button").click(function() {

    $.post("commandrunner.php",
        {
            param1: 'value',
            param2: 'value2',
            param3: 'value3'
        },
        function(data, textStatus) {
            $(this).parent().after('<p>button clicked</p>')
        },
        "json"
    );

});

The issue here is that when jQuery called the function again, it did not call it with the same this. When you create an anonymous function, it will hold onto all local variables in the same scope, but not this, which is set by JavaScript itself (to the global object) or overridden when called.

As a result, the solution is to store off a pointer to this in a local variable, which will then be available to the closure.

The solution, as mentioned above, is:

$(".button").click(function() {
  var parent = $(this).parent();
  $.post("commandrunner.php",
    {
      param1: 'value',
      param2: 'value2',
      param3: 'value3'
    },
    function() {
      parent.after('<p>button clicked</p>')
    },
    "json"
  );
});

In general, when I store off a local, I store off the most specific set of elements I can, to make the callback code simpler. The common jQuery idiom is to do var self = this, which is perfectly fine as well.

Also note that JavaScript functions do not check the number of parameters, so it's perfectly legal to leave the parameters empty if you do not use them. They will still be passed in, but the empty parameter list will simply be ignored.

like image 188
Yehuda Katz Avatar answered Sep 25 '22 05:09

Yehuda Katz


According to jquery api (under "Callback Function Queues") the this object in any JQuery AJAX callback function will automatically point to the settings of the ajax object or - if specified - the context object.

Sadly you cannot specify a context in $.post().

like image 25
p.sherif Avatar answered Sep 22 '22 05:09

p.sherif