Currently I have a jQuery plugin which not only sets up its function in $.fn
but also $
itself, checking if (typeof(this) == 'function')
to see if it has been called through $.pluginname
or $(elm).pluginname
... is this bad practice, and if so, is there a better way to make providing the element optional?
views:
100answers:
2The jquery extend function is exposed on both namespaces:
The jQuery source defines both as:
$.extend = $.fn.extend = ...
This would lead me to believe that they intended for you to be able to do this. However, if you look at the way the jQuery authors have set up their own functions to use both, you may get a better idea of the best practice.
For instance, you would normally want the $.fn function to call the $ function. (Much like the $.data function in the jQuery source)
$.extend({
data: function(elem, key, value) {...}
});
and (a bit simplified):
$.fn.extend({
data: function(key, value){
return this.each(function(){
$.data(this, key, value);
};
}
});
This way, one calls the other and takes care of the check for which version you are using, and if you wanted to, you could just check for an undefined 'elem' param in the $ namespace.
Have you had a read through the jquery authoring docs? The log function in the example is considered the standard way of adding functions to the jquery object for developers.