Manish Rawat
Manish Rawat

Reputation: 1212

jQuery plugin with multiple methods

I am going to wrap some of my functions in a nice manner and for this I want to go with jQuery approach. Like jQuery having a lots of methods

$.parseJson()
$.ajax()
$("div").text("hey my testing");

and both methods are present in a same jQuery file. But while reading about how to make a jquery plugin, its specified that you don't need to create multiple functions inside a same plugin. Instead pass an argument which contains the method name as string.

So, Is that the below snippet is correct or do i need to make some corrections in it.

<script type="text/javascript">
    (function ($) {
        $.fn.testMethod1 = function () {
            return $(this).each(function () { });
        };
        $.fn.testMethod2 = function () {
            return $(this).each(function () { });
        };
        $.test = function () {
            return "testresult"
        };
    })(jQuery);

    $("div1").testMethod1();
    $("div2").testMethod2();
    $.test();

    //Is that needed to be replace in a different way like
    $("div1").myPlugin("testMethod1");
    $("div1").myPlugin("testMethod2");
    $("div1").myPlugin("test");


</script>

Upvotes: 0

Views: 2870

Answers (2)

lngs
lngs

Reputation: 698

Have you try using jquery boilerplate. It is a good point to start study jQuery plugin development. It's provide a safe and(seem to be) a good solution to create a plugin. They use your second way to call a method.

Upvotes: 1

PitaJ
PitaJ

Reputation: 15012

The second way is preferred because it conserves namespace in the jQuery object.

Read the official jQuery doc for this: Plugins/Authoring

Upvotes: 1

Related Questions