Reputation: 3136
I'm learning more about making jQuery plugins, and I'm at a point where I'm trying to make public member functions. I'm doing it via the method I've seen in a bunch of plugins:
$.fn.pluginName = function () {
// $(this) contains the selector (#test)
}
$.fn.pluginName.publicFunction = function () {
// How do I get $('#test') here?
}
$('#test').pluginName();
$('#test').pluginName.publicFunction();
I'm wondering how I can access the selector used in selecting the main plugin within the public function, or if I have to pass it in order to use it. Any advice? I think I know how to do it with private functions, but I'm at a bit of a loss with this.
The first two answers make it obvious I wasn't clear, so the question has been updated.
Upvotes: 0
Views: 1049
Reputation: 707158
Inside the function of a jQuery plugin function:
this.selector
will be the original selector passed to the original jQuery object. I can't tell for sure, but this may be deprecated in the latest versions of jQuery, though it is still present in jQuery 2.0.2.
Working demo here:
http://jsfiddle.net/jfriend00/JczB9/
$.fn.test = function() {
// this.selector contains #test from the original jQuery selector
};
var item = $("#test");
item.test();
If you're trying to get access to the jQuery instance (to get the original selector) from a public method on your jQuery plugin such as $('#test').pluginName.publicFunction();
in your example, you can't.
The selector is a property of a jQuery instance only so only methods of a jQuery instance or functions who have a reference to a jQuery instance are going to be able to access the .selector
property.
$('#test').pluginName
is a static function object (e.g. there's only one of them) - it isn't a jQuery instance so $('#test').pluginName.publicFunction()
doesn't have access to the properties of $('#test')
and thus can't get to the selector.
If I understood why you were making public functions on your jQuery plugin and what you were trying to do with it, I might have an alternate solution for you.
For example, your publicFunction()
could itself be a jQuery plugin method and then you could use chaining like $('#test').pluginName().publicFunction()
.
Upvotes: 1
Reputation: 799
if you want a global selector for your function (is that what you mean) you do this:
window.publicSelector = privateSelector
then from public javascript code, it should be accessible using publicSelector
Upvotes: 0