$.myPlugin
The recommended way to solve your problem is using this
and other methods described below. If you require the selector as a string, you can define the function as a child of jQuery ($
) and have the function executed in a similar way to jQuery's &.ajax and $.extend. What this is doing is it is making it a child of jQuery, and a child of $.fn
so it can still be 'classified' as a regular jQuery plugin, or a prototype of jQuery. When you old set your plugin the $.fn
, it is set to jQuery's prototype, making it so you have to run the jQuery function. Here we are doing that, but because functions are also objects, we can set that function to $.myPlugin making it still part of jQuery, but prevents the user from entering the selector twice. Since this.selector
s deprecated (and it'll probably be removed soon) it's better than running it through a function to generate a selector.
$.myPlugin = $.fn.myPlugin = function (selector) {
console.log(selector);
}
$.myPlugin('#selector'); //Logs: '#selector
The $.fn is completely optional and is there just in case a user forgets to execute the function using $.myPlugin(selector)
the function will still work when using $().myPlugin(selector)
Other alternative
If you don't require the string, I would recommend using jQuery's .filter() or similar functions (here) along with $(this)
.
$.fn.myPlugin = function () {
var $this = this;
var filteredElements = $this.children('a');//
console.log(filteredElements);
}
$('#form .class').myPlugin();
//Logs: children that are <a> of #form .class