0

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>
7
  • 1
    this is already a jQuery object. You don't need to re-wrap it. Commented Mar 8, 2013 at 5:10
  • Ok, accepted. But is that multiple methods inside a same plugin is correct? Commented Mar 8, 2013 at 5:11
  • Twitter Bootstrap does it that way and I think it's more intuitive if all plugins followed the same syntax. Commented Mar 8, 2013 at 5:13
  • @Blender - the first way or the second way? Commented Mar 8, 2013 at 5:15
  • @Blender But its something like we are calling the plugins through their name. e.g. $("div").myPlugin("externalPlugin1",data) and $("div").myPlugin("externalPlugin2") Commented Mar 8, 2013 at 5:29

2 Answers 2

1

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

Read the official jQuery doc for this: Plugins/Authoring

Sign up to request clarification or add additional context in comments.

2 Comments

What you mean by conserving namespaces in jQuery. There are already a bunch of pre-defined functions in jQuery so why don't they do it in the same way like $("div")("fadeIn")
It's just the preferred way for most developers. This allows for there to be more plugin possibilities without there being really complex names. It's just the preferable standard.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.