wmarbut
wmarbut

Reputation: 4705

jQuery plugin method that doesn't take an element

I'm authoring a jQuery plugin in which one of the methods that I'd like to write will not take a selector argument and does not need to pass an element. I'd like it to be available by a call like $.myMethod() like the built in $.ajax() method. Up to now I've tried something like

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

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

Is this doable with a jQuery plugin or is it only available for interal functions.

The purpose of this method is to perform an action on some data that is stored in jQuery.data. I recognize that they jQuery.data is associated with an element, but in this case I've hard coded it to the body element to make things easier for the end user.

Upvotes: 3

Views: 134

Answers (2)

Ahamed Mustafa M
Ahamed Mustafa M

Reputation: 3139

An elaborate way of declaring such a function can be

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

Upvotes: 0

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263157

The functions that are members of $.fn apply to jQuery objects, not to the $ object itself. If you want to create such a method, you only have to write:

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

Now you can call it without a jQuery object:

$.yourMethod();

Upvotes: 2

Related Questions