Jquery 在AJAX回调之后,如何维护对特定插件实例的引用?

Jquery 在AJAX回调之后,如何维护对特定插件实例的引用?,jquery,jquery-plugins,Jquery,Jquery Plugins,我想在创建插件时触发一个AJAX调用,该插件将检索一些数据,然后继续构建插件控件。因此,考虑到这个简化版本: $.fn.grid = function (options) { this.each(function () { var $this = $(this); // Somehow to maintain $this for the callback buildPluginBasics($this); $.getJSON("Data

我想在创建插件时触发一个AJAX调用,该插件将检索一些数据,然后继续构建插件控件。因此,考虑到这个简化版本:

$.fn.grid = function (options) {
    this.each(function () {

        var $this = $(this); // Somehow to maintain $this for the callback
        buildPluginBasics($this);

        $.getJSON("DataPath", { option1:"etc" }, dataReceived);

    });

    function dataReceived(data, status) {
        buildGridRows($theCallingInstance, data);
    }
}
你可以看到,我没有办法知道我现在需要继续构建哪个插件元素。我基本上需要一个对原始
$this
的引用才能在
dataReceived
中找到。有人能给我指出正确的方向吗?

您可以使用带有
上下文
选项的完整调用,如下所示:

$.ajax({
  context: $this,
  url: "DataPath",
  dataType: 'json',
  data: { option1:"etc" },
  success: dataReceived
});
在您的方法中,
将是上面的上下文,因此,
$this
来自原始

function dataReceived(data, status) {
    //this == $this from before
    buildGridRows(this, data);
}

或者,使用匿名方法并传递附加参数,例如:

$.getJSON("DataPath", { option1:"etc" }, function(data, status) {
  dataReceived(data, status, $this);
});
并将其作为参数添加到方法中:

function dataReceived(data, status, obj) {
    //obj == $this
    buildGridRows(obj, data);
}
您可以通过
上下文
选项使用完整调用,如下所示:

$.ajax({
  context: $this,
  url: "DataPath",
  dataType: 'json',
  data: { option1:"etc" },
  success: dataReceived
});
在您的方法中,
将是上面的上下文,因此,
$this
来自原始

function dataReceived(data, status) {
    //this == $this from before
    buildGridRows(this, data);
}

或者,使用匿名方法并传递附加参数,例如:

$.getJSON("DataPath", { option1:"etc" }, function(data, status) {
  dataReceived(data, status, $this);
});
并将其作为参数添加到方法中:

function dataReceived(data, status, obj) {
    //obj == $this
    buildGridRows(obj, data);
}

非常感谢你!很好,非常感谢!完全正确