В каком контексте jQuery.post функция обратного вызова вызывается?

Для завершения других ответов:

Синхронизация вызывает беспокойство только тогда, когда код в вашем методе выполняет одно из двух действий:

  1. работает с некоторым внешним ресурсом, который не является потоком безопасный.
  2. Считывает или изменяет постоянный объект или поле класса

Это означает, что переменные, определенные в вашем методе, всегда являются потокобезопасными. Каждый вызов метода имеет свою версию этих переменных. Если метод вызывается другим потоком или тем же потоком, или даже если метод вызывает сам себя (рекурсия), значения этих переменных не разделяются.

Планирование потоков не гарантируется как циклический перебор . Задача может полностью перегружать процессор за счет потоков с одинаковым приоритетом. Вы можете использовать Thread.yield (), чтобы иметь совесть. Вы можете использовать (в Java) Thread.setPriority (Thread.NORM_PRIORITY-1), чтобы понизить приоритет потока

Плюс, остерегайтесь:

  • больших затрат времени выполнения (уже упоминавшихся другими ) в приложениях, которые перебирают эти «потокобезопасные» структуры.
  • Thread.sleep (5000) должен спать в течение 5 секунд. Однако, если кто-то изменит системное время, вы можете спать очень долго или вообще не спать. ОС записывает время пробуждения в абсолютной форме, а не в относительной.

7
задан Ali 30 June 2009 в 21:38
поделиться

3 ответа

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.

12
ответ дан 6 December 2019 в 11:51
поделиться

Это правильный подход к проблеме.

Самый простой способ узнать контекст - использовать Firebug и console.log (это ) - Я подозреваю, что это будет объект XHR.

0
ответ дан 6 December 2019 в 11:51
поделиться

Ключевое слово this привязано к области видимости функции. Чтобы ссылаться на другие родительские области, вам необходимо сохранить ссылку в соответствующих переменных области, например var parentScope = this;

0
ответ дан 6 December 2019 в 11:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: