开发者

How can I maintain reference to a particular plugin instance after an AJAX callback?

开发者 https://www.devze.com 2023-01-15 07:33 出处:网络
I want to fire off an AJAX call when a plugin is created that will retrieve some data and then continue building the plugin control. So given this simplified version:

I want to fire off an AJAX call when a plugin is created that will retrieve some data and then continue building the plugin control. So given this simplified version:

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

You can see I've not got any way of knowing which plugin element I now need to continue building. I basically need 开发者_StackOverflow社区a reference to the original $this to be available in dataReceived. Can anyone point me in the right direction?


You can use the full $.ajax() call with the context option, like this:

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

And in your method, this will be the context above, so $this from the original.

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

Alternatively, use an anonymous method and pass an additional argument, e.g.:

$.getJSON("DataPath", { option1:"etc" }, function(data, status) {
  dataReceived(data, status, $this);
});

And add it as a parameter on your method:

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

精彩评论

暂无评论...
验证码 换一张
取 消