JQuery plugin method that does not accept an element

I am creating a jQuery plugin in which one of the methods I would like to write will not accept a selector argument and should not pass an element. I would like it to be available on a type call $.myMethod(), as an inline method $.ajax(). So far I have tried something like

$.fn.myMethod(options) {
     console.log("I've been called");
}

It works when I try $('.a_selector').myMethod(), but not when I try $.myMethod().

This is possible using the jQuery plugin or is only available for gateway functions.

The purpose of this method is to take action on some data that is stored in jQuery.data. I admit that they are associated with the jQuery.data element, but in this case I hard-coded it for the body element to make the task easier for the end user.

+3
source share
2 answers

The member functions $.fnapply to jQuery objects, not the object $. If you want to create such a method, you only need to write:

$.yourMethod = function() {
    // Do something.
};

Now you can call it without a jQuery object:

$.yourMethod();
+2
source

A developed way to declare such a function may be

$.extend({myMethodA:function(){
                            //Do something
                            },
          myMethodB:function(){
                        //Do something else
                                }       
                 });
0
source

All Articles