0

In the jQuery plugin I have created, to access its methods from outside the plugin I have to do something like

$("#testItem").data('pluginName').foo_public_method()

However, I have seen other plugins offer an API along the lines of

$('#testItem').pluginName('foo_public_method')

How do I enable this sort of functionality?

jsFiddle

Fisu
  • 3,294
  • 9
  • 39
  • 61

1 Answers1

1

You need to interrogate the arguments which were passed to the plugin instance, and check if the plugin has already been instantiated on the element.

From the look of your example, the plugin instance is stored in the data property for the element, so this should be straightforward to check for. You can then use the arguments keyword to access anything which has been passed in.

In the code below, I'm taking this to be a single element which the plugin was called on.

var instance = $(this).data('pluginname');
var args = $.makeArray(arguments);
if (!instance) {
    // create the plugin on the element using args as an object
}
else {
    // plugin already exists
    if (typeof args[0] == "string") {
        // arg0 = property
        // arg1 = value
    }
    else {
        // logic for passing in arguments as an object
    }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • I partly understand, but still a little confused - does the argument interrogation need to happen in the `$.pluginName = function(element, options)` function or the `$.fn.pluginName = function(options)` function? – Fisu Aug 13 '13 at 12:11