Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a jQuery plugin function callable for stand-alone use, that does not operate on a collection

I read the jquery documentation of plugin authoring and am familiar with that. However, the examples given always operate on a set of previously matched elements. I want to create a function that can do both:

// example usage of my to-be-created plugin function

// this is the way described in the docs, and I know how to do that
$("a").myFunction ()

// but I also want to be able to call the function without a collection:
$.myFunction ();

If $.myFunction ()is called without a collection to operate on, it would create it's own collection of what elements to match - kind of an initialization process (but not necessarily run only once). Also, $.myFunction ()should maintain chainability.

The pseudocode of what I want to achieve:

// [...]
function myFunction (): {
    if (notCalledOnACollection) {
        // this should run when called via $.myFunction ()
        $elements = $("a.myClass");
    }
    else {
        $elements = $(this);
    }
    return $elements.each (function () {
        // do sth. here 
    });
}

I would really like to keep all of the functions implementation/functionality within a single function definition, and not have two separately named functions or two equally named functions in two separately places within the jQuery object.

And of course I could add a parameter myFunction (do_init) that indicates what branch of the if statement to execute, but that would clutter my argument list (I want to use that approach for multiple plugins, and there will be argumentes to myFunction () that I just left out here for simplicity).

Any good suggestions?

like image 252
Dynalon Avatar asked Sep 14 '12 07:09

Dynalon


1 Answers

By simply adding another reference in the plugin definiton, you can easily use the standard plugin code:

(function( $ ) {
    $.myPlugin = $.fn.myPlugin = function(myPluginArguments) {
        if(this.jquery)
            //"this" is a jquery collection, do jquery stuff with it
        } else {
            //"this" is not a jquery collection
        }
    };

    $.fn.myPlugin.otherFunc = function() {
    };
})( jQuery );

The only difference here is the $.myPlugin = part which allows you to directly call your plugin without running jquery's selector function. Should you decide you need other functions or properties, you can create them as properties of your plugin.

Usage:

//using a selector (arguments optional)
$(".someClass").myPlugin();

//using the options variable - or whatever your arguments are
$.myPlugin({id: "someId"});

//accessing your other functions/properties
$.myPlugin.otherFunc();
like image 138
uɥƃnɐʌuop Avatar answered Nov 15 '22 02:11

uɥƃnɐʌuop