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.

2 Kommentare:

  1. Hey, i like your new blog and i totally understand your anger. perhaps you should use a text-editor (or google docs for that matter) to create the posts before submitting them so we can get your beautifully written posts instead of this abbreviated form next time :).
    as for the code: i noticed you are only error-checking if a method exists on the topmost level and only if you are actually calling a topmost level function. so i tried fixing this and simplified a few other things along the way: http://pastie.org/2955248
    i hope you find it useful :) (disclaimer: this is fully drycoded, so no guarantees that it actually works :P)

    AntwortenLöschen
  2. Hi Reimond,

    thx a lot for your feedback. As soon as I have some spare time I will update the snippet.

    AntwortenLöschen