tags:

views:

22

answers:

1

I'm writing a jQuery plugin to render data retrieved from another domain in an element on the page. I follow the typical pattern for my jQuery plugin:

$(selector).Plugin(options);

In the plugin I get external data using jQuery.getScript(url, [success]). The external data source allows me to define the name of a method and it will wrap the data in a call to that method (JSONP):

$.getScript("http://www.example.com/data?callback=global_callback", instance_callback);

This effectively results in:

<script type="text/javascript">
  global_callback(data);
</script>

The scope of global_callback limits what the Plugin instance can do with the data. And the global_callback method has no knowledge of the selector or options that the plugin was instantiated with.

I was thinking that global_callback would just store the data, and the plugin would retrieve the data in instance_callback. But I need to make sure that instance_callback will retrieve the correct data, I foresee a problem with multiple instances of the Plugin. How can I handle this?

Thanks!

+1  A: 

I may not understand what you are asking. These callbacks work similar to regular JSON, except that you can name the callback (if you want). The execute within the context of the AJAX, but of course this is not available unless you assign it to a different variable.

If you made your call like this, you would not even need to name your callback:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?", function(data){
  $.each(data.items, function(i,item){
    $("<img/>").attr("src", item.media.m).appendTo("#images")
      .wrap("<a href='" + item.link + "'></a>");
    if ( i == 3 ) return false;
  });
});

Reference: http://docs.jquery.com/Release:jQuery_1.2/Ajax#Cross-Domain_getJSON_.28using_JSONP.29

If you are concerned with running in the instance of your plugin, wrap this call in a closure. This way you can reference whatever instance you need to access during the callback.

function GetSomeData(){
  var that = this; //reference to the element you are working
  $.getJSON("...",function(data){
    //do some stuff to element with data
    $("element").data("JSONP",data);
  });

}
Drew
Great, I didn't know about $.getJSON(), it seems to fix the issue by generating a function with a unique name for each request, so I can get rid of my global callback function and I probably don't have to worry about concurrency.Thanks!
michielvoo