views:

18

answers:

1

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 a reference to the original $this to be available in dataReceived. Can anyone point me in the right direction?

+4  A: 

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);
}
Nick Craver
@Nick Craver - Thank you very much! Spot on.
GenericTypeTea
@GenericTypeTea - welcome!
Nick Craver