Fisu
Fisu

Reputation: 3324

How to add standard API functionality to jQuery plugin

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

Upvotes: 0

Views: 122

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

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
    }
}

Upvotes: 1

Related Questions