代码之家  ›  专栏  ›  技术社区  ›  djdd87

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

  •  1
  • djdd87  · 技术社区  · 14 年前

    我想在创建一个插件时触发一个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 回复  |  直到 14 年前
        1
  •  4
  •   djdd87    14 年前

    你可以用完整的 $.ajax() 打电话给 context 选项,如下所示:

    $.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);
    }