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

前端 未结 4 1637
清酒与你
清酒与你 2020-12-31 22:12

Lets say for example:

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

    $.post(\"commandrunner.php\",
        {
            param1: \'value\',
            param2: \'val         


        
相关标签:
4条回答
  • 2020-12-31 22:29

    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.

    0 讨论(0)
  • 2020-12-31 22:33

    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().

    0 讨论(0)
  • 2020-12-31 22:37

    That is the right approach to the problem.

    The easiest way to find out the context would be to use Firebug and console.log(this) — I suspect it would be the XHR object though.

    0 讨论(0)
  • 2020-12-31 22:40

    The keyword "this" is bound to the scope of a function. To reference other parent scopes you need to store the reference in appropriate scoping variables, such as var parentScope = this;

    0 讨论(0)
提交回复
热议问题