Donnerstag, 1. Dezember 2011

How to implement and call nested methods on a jQuery plugin

Hello whatever,
after I wrote nearly a page on this damn blog my chrome tab simply crashed. Thx a lot. So here is the short version:
  • First official post
  • Why did I start a blog and why on this platform --> Read here
  • Wrote my first jQuery plugin for a customer
  • the way calling methods, described in plugin authoring guidelines, didn't suit my needs
  • wanted to be able to call nested methods
To make a call like this 
$('#someElement').myPlugin('util.someMethod');

I ended up with this:

var methods = { 
   util : {
      someMethod : function() {
         //do something
      }
   }
}

$.fn.myPlugin =  function(method){ 
    //calling nested methods
    var m = '';
    if (method.indexOf('.') > -1) {
        var objArray = method.split('.');
        var m = methods[objArray[0]];
        for (var i=1; i < objArray.length; i+=1) {
            m = m[ objArray[i] ];
        }
        return m.apply( this, 
           Array.prototype.slice.call( arguments, 1 ));
    } 
    //default way
    else if ( methods[method] ) {
       return methods[ method ].apply( this, 
                 Array.prototype.slice.call( arguments, 1 ));
      }       
      else {
       $.error( 'Method ' +  method + 
                 ' does not exist on jQuery.myPlugin' );
    }           
 };
Comments and improvements welcome.
Did I mention that I'm angry because the damn page crashed?

The Blog title is "work in progress". ;)

Thank you D. Schopper for helping me with this solution.