GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, February 21, 2011

jQuery Plugin Authoring

In this moment, the code below show to you on how to build your own plugin that namespacing. Without namespacing, the code is like below:

<script src="jquery-1.5.js"></script>

<div id="satu">
Indonesia
</div>

<script>
function($){
     $.fn.fore = function(options){
         var settings = {
             'color': 'blue'
         };
         if(options){
             $.extend(settings, options);
         }
         $(this).css('color',settings.color);
         return $(this);
     };

     $.fn.back = function(options){
         var settings = {
             'color': 'lime'
         };
         $(options){
             $.extend(settings, options);
         }
         $(this).css('background',settings.color);
         return $(this);
    };
})(jQuery);

$('#satu').fore().back();

</script>

But with the namespace, the code will be like this:
<script src="jquery-1.5.js"></script>

<div id="satu">
Indonesia
</div>

<script>
function($){
    var methods = {
        // this is the same function in the above 
        // this is the first function in the above           
        'fore': function(options){
            var settings = {
                'color': 'blue'
            };
            if(options){
                $.extend(settings, options);
            }
            $(this).css('color',settings.color);
            return $(this);
        },

        // this is the second function of the above
        'back': function(options){
            var settings = {
                'color': 'lime'
            };
            if (options){
                $.extend(settings, options);
            }
            $(this).css('background',settings.color);
                return $(this);
            }
        };

// this is the main function of namespacing
$.fn.coloring = function(method){
    if ( methods[method] ) {
        return methods[ method ].apply( this, 
                  Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
    } else {
        $.error( 'Method ' +  method + ' does not exist on ' 
                 + ' jQuery.tooltip' );
    }   

}
 
})(jQuery);

$('#satu').coloring('fore').coloring('back');

</script>
Share/Bookmark

No comments:

Post a Comment