Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Or is it already well designed? I've used this for a couple years on jobs and it has been great. I love my template -- especially since i made it -- but recently I've caught myself giving this great secret away as an answer to some questions. So now I'm wondering, what do you think of my template? How might I improve it? Do you see any flaws (I've yet to discover any)? Should I blog it and pass it around a bit more?

In short, please "Code Review" it!

/*  Example Plug-in Setup   */
(function($) {
    if (!$.myExample) { // check your plugin namespace does not already exist
        $.extend({  //  this will allow you to add your plugin to the jQuery lib
            myExample: function(elm, command, args) {
                //  keep in mind, right here you might want to do a class or data check to determine which direction this call is going
                //  for example, upon init the plugin on an element you may add the plugin name as a class, 
                //      this way, when it's recalled, you can see it alrady has that class and might be calling a command,
                //          thus make an if statemnt to push the process through
                return elm.each(function(index){
                    // do work to each element as its passed through
                    // be sure to use something like
                    //    return elm.each(function(e) { dor work });
                    // as your final statement in order to maintain "chainability"
                });
            }
        });
        $.fn.extend({   //  this gives the chainability functionality seen with $ funcs like: $("#eleID").css("color", "red") <--returns original element object
            myExample: function(command) {
                return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1));
            }
        });
        $.myExample.props = {   //  Here you can establish specific properties to your plugin, prehaps even make them "Over-writable"
            key1: "value",
            key2: "value"
        };
        $.myExample.methods = { //  Here you can establish specific methods/functions for your plguin to carry out and maintain your namespace as well
            key1: function(param) {
                /*  do work */
            },
            key2: function(param) {
                /*  do work */
            }
        };
        //  This next part is not seen in many plugins but useful depending on what you're creating
        $.myExample.init = function(param) {    //  If you have an initialize method to apply, namespace it in here and calll on initializing your plugin
            var key = "value",
                key2 = {
                    subKey: "value"
                };
                /*
                /  run any number of initializing functions here
                /  I prefer to make my param a value that can be a
                /   string with a possible object
                /   the string for holding a base configuration
                /   the object for any change in properties or base values for that config
                */
        };
        $.myExample.defaults = {    //  establish base properties here that can be over-written via .props, but their values should never truly change
            key1: "value",
            key2: {
                prop1: {
                    subKey1: "value",
                    subKey2: "value"
                },
                prop2: {
                    subKey1: "value"
                }
            },
            key3: function(param) {

            }
        };
    }
})(jQuery);

Uses

$("#eleID").myExample();
//  OR
$.myExample($("#eleID"));
share|improve this question
    
Hmm, i would push you over to addyosmanis jquery plugin patterns. There are many great approaches, to learn from :) –  yckart Dec 3 '12 at 10:47

1 Answer 1

up vote 0 down vote accepted

Updated!


I've had more time to make more plugs and thus more improvements to my overall template. That being said, keep in mind, this is ONLY a template. Thus you may still want to make changes to further your own specific needs.

Another thing to note, this base template is meant to be run on possibly existing elements that need to be altered. However, there are very easy markers left in for making any possible change needed in order to fuel your own desires.

All of that being said, I've commented this thing out plenty. So I'll let this new version speak for itself.

(function($) {
    if (!$.myExample) {
        $.extend({
            myExample: function() {
                var args = arguments,
                    aArray, aBool, aFunc, aInt, aObj, aString,
                    elm;
                //  preset arguments to variables
                if (args.length) {
                    for (x in args) {
                        switch (typeof args[x]) {
                            case 'boolean':
                                aBool = args[x];
                                break;
                            case 'function':
                                if (!aFunc) aFunc = args[x];
                                //  in case there are multple callbacks, example: $.myExample(function(on){}, function(off){})
                                else if (typeof aFunc == "function") aFunc = [ aFunc, args[x] ];
                                else if (typeof aFunc == "object") aFunc.push(args[x]);
                                break;
                            case 'number':
                                aInt = args[x];
                                break;
                            case 'object':
                                //  distinguish between Arrays and Objects passed in
                                args[x] instanceof Array ? aArray = args[x]: args[x] instanceof jQuery ? elm = args[x] : aObj = args[x];
                                break;
                            case 'string':
                                aString = args[x];
                                //  check to possibly set "elm" if your expect a jQuery Object to be used
                                //  modify this procedure as needed
                                if (!elm) {
                                    //  may check to see if jquery version has "length" (exist on Document)
                                    //  remove if statement if you want string always accepted as element ID|ClassName|TagName
                                    if ($(aString).length) elm = $(aString);
                                    //  this could also be an area to check for "commands",
                                    //  meant to be given to plugin already in play on a specific element
                                }
                                break;
                        }
                    }
                }

                if (elm instanceof jQuery) {
                    return elm.each(function(index){
                        // do work to each element as its passed through
                    });
                }
                else {
                    /*  No element provided, either none is expected
                     *  or this could be an erroneous call.
                     *  This might be useful if using plugin to pass back a custom object   */
                    return arguments;
                }
            }
        });
        $.fn.extend({
            myExample: function(/*no need for parameter names here as arguments are evaluated inside and passed on to initial method*/) {
                //  set this element as first argument to fit with initial plugin method
                var args = [$(this)];
                //  if there are arguments/params/options/commands too be set, add them
                if (arguments.length) for (x in arguments) args.push(arguments[x]);
                //  pass through jquery and our arguments, end result provides same arguments as if the call was:
                //      $.myExample($(element), options)
                return $.myExample.apply($, args);
            }
        });
        $.myExample.props = {   //  Here you can establish specific properties to your plugin, prehaps even make them "Over-writable"
            key1: "value",
            key2: "value"
        };
        $.myExample.methods = { //  Here you can establish specific methods/functions for your plguin to carry out and maintain your namespace as well
            key1: function(param) {
                /*  do work */
            },
            key2: function(param) {
                /*  do work */
            }
        };
        //  This next part is not seen in many plugins but useful depending on what you're creating
        $.myExample.init = function(param) {    //  If you have an initialize method to apply, namespace it in here and calll on initializing your plugin
            var key = "value",
                key2 = {
                    subKey: "value"
                };
                /*
                /  run any number of initializing functions here
                /  I prefer to make my param a value that can be a
                /   string with a possible object
                /   the string for holding a base configuration
                /   the object for any change in properties or base values for that config
                */
        };
        $.myExample.defaults = {    //  establish base properties here that can be over-written via .props, but their values should never truly change
            key1: "value",
            key2: {
                prop1: {
                    subKey1: "value",
                    subKey2: "value"
                },
                prop2: {
                    subKey1: "value"
                }
            },
            key3: function(param) {

            }
        };
    }
})(jQuery);

If you've read all this before and simply here for a "Ready to Go!" version, just copy and paste the following:

(function($) {
    if (!$.myExample) {
        $.extend({
            myExample: function() {
                var args = arguments,
                    aArray, aBool, aFunc, aInt, aObj, aString,
                    elm;
                if (args.length) {
                    for (x in args) {
                        switch (typeof args[x]) {
                            case 'boolean':
                                aBool = args[x];
                                break;
                            case 'function':
                                if (!aFunc) aFunc = args[x];
                                else if (typeof aFunc == "function") aFunc = [ aFunc, args[x] ];
                                else if (typeof aFunc == "object") aFunc.push(args[x]);
                                break;
                            case 'number':
                                aInt = args[x];
                                break;
                            case 'object':
                                args[x] instanceof Array ? aArray = args[x]: args[x] instanceof jQuery ? elm = args[x] : aObj = args[x];
                                break;
                            case 'string':
                                if (!aString) {
                                    aString = args[x];
                                    if (!elm) elm = $(aString);
                                }
                                else if (typeof aString == "string") aString = [ aString, args[x] ];
                                else if (typeof aString == "object") aString.push(args[x]);
                                break;
                        }
                    }
                }

                if (elm instanceof jQuery) {
                    return elm.each(function(index){

                    });
                }
                else {
                    return 'Error: Cannot find Selector';
                }
            }
        });
        $.fn.extend({
            myExample: function() {
                var args = [$(this)];
                if (arguments.length) for (x in arguments) args.push(arguments[x]);
                return $.myExample.apply($, args);
            }
        });
        $.myExample.init = function() {};
        $.myExample.defaults = {};
        $.myExample.methods = {};
        $.myExample.props = {};
    }
})(jQuery);

Have fun and enjoy! I have!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.