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

时间:2010-09-04 11:14:36

标签: jquery jquery-plugins

我想在创建一个插件时触发一个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的引用。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:4)

您可以使用context选项进行完整的$.ajax()调用,如下所示:

$.ajax({
  context: $this,
  url: "DataPath",
  dataType: 'json',
  data: { option1:"etc" },
  success: dataReceived
});

在您的方法中,this将是上述背景,因此原始版本为$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);
}
相关问题