views:

61

answers:

3

Say I have the following jQuery plugin:

$.fn.myPlugin = function () {
    //plugin code
}

Normally, you call a plugin on a certain number of elements, like such:

$("body").myPlugin();


Is there any way I can call my plugin without specifying an element?

I have tried calling it like such: $.myPlugin();, but that does not work.

What works is this: $().myPlugin();, but is that the correct way to invoke it?

A: 

Does it use the collection if you write something different, like $('a').myPlugin()? If it doesn't, then why are you putting it in $.fn? Maybe you wanted to inject it into jQuery itself.

If it does work on a collection, but sometimes an empty collection makes sense, then I think that your invocant should be $([]) -- passing an empty Array to jQuery gives you an empty collection; passing nothing at all seems to give you a collection containing document.

hobbs
No it doesn't need any elements to work on; that's why I need it to be called without any elements
Andreas Grech
So I should change it to `$.myPlugin = function ()` instead of using the `fn` ? because I tried it now like that, and I can infact call it then with the notation I want: `$.myPlugin();`
Andreas Grech
And if I use `$.myPlugin = function ()`, will it still technically be called a `plugin` ?
Andreas Grech
+2  A: 

The quick way to write it is this:

$.myPlugin = function () {
    // Plugin code
}

The right way to write it is this:

(function ($) {
    $.extend({
        myPlugin: function () {
            // plugin code
        }
    });
})(jQuery);

It might seem a little confusing at first, but it's a common jQuery pattern.

(function($){
     // Code
})(jQuery);

This code creates an anonymous function and calls it passing jQuery as argument. Inside the function this argument is bound to $. The reason this is done it that it allows you to work with the $ even if jQuery is running in no-conflict mode.

The second part is $.extend. It basically extends the jQuery object itself, when called with a single argument.

Calling the plugin (in the quick and the right case) is:

$.myPlugin();
Emil Ivanov
I know about that pattern :) I just didn't use it in the question to avoid code cluttering. But thanks for the extend method!
Andreas Grech
A: 

I think you're looking for jQuery.extend() :

jQuery.extend({
    func: function() {
        alert('test');
    }
});
$.func();
I.devries