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!
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:
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.