0

I'm starting to write more jQuery plugins within their own namespace so I can re-use code and to keep my code DRY.

I'm new to the whole plugin authoring, but read a few sources including the official jQuery one.

Here is an example I found that I'm playing around with:

(function($) {
    // jQuery plugin definition
    $.fn.reverseText = function(params) {
        $.fn.reverseText.test();
        // merge default and user parameters
        params = $.extend({
            minlength: 0,
            maxlength: 99999
        }, params);
        // traverse all nodes
        this.each(function() {
            console.log($(this).parent().data('url'));
            // express a single node as a jQuery object
            var $t = $(this);
            // find text
            var origText = $t.text(),
                newText = '';
            // text length within defined limits?
            if (origText.length >= params.minlength && origText.length <= params.maxlength) {
                // reverse text
                for (var i = origText.length - 1; i >= 0; i--) newText += origText.substr(i, 1);
                $t.text(newText);
            }
        });
        // allow jQuery chaining
        return this.each;

    };
    // Is this correct?
    $.fn.reverseText.test = function() {
    alert('test');
    };
})(jQuery);


$(function() {
    $(".js-test-whatever li:even").reverseText();
});

Generally I'd create a namespace like this:

 var a = {

    };

    a.reverseText = {
        init: function () {
         reverseText(); 
        });
    },

    reverse: function() {
     $(function() {
        return foo;
      });
    }

    a.reverseText.init();

So what's the proper way to add multiple functions within a jQuery plugin namespace?

Look at the comment in the first example of where I included an additional function.

1 Answer 1

1

That is an acceptable way to do it. Another way to do it could be like this:

(function($) {
    var reverse = {
        test: function () {
            alert('test');
        },

        fn: function(params) {
            reverse.test();

            /* the rest of your plugin code */
        }
    }

    // jQuery plugin definition
    $.fn.reverseText = reverse.fn
})(jQuery);

There is no one "correct" way. Just use whatever works best for the project that you are currently working on.

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

1 Comment

Cool thanks alec :) I'll try that way out and see how I like it.

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.