Thursday, April 17, 2008



This small plugin(673 bytes!) enables you to have modular methods on jQuery.
It allows the developer to apply the module pattern, to the functions of jQuery.fn.
They can be used as namespace/module for more functions.
This helps keeping the rule of only claiming one name from the jQuery namespace.


It takes a module declared like this:
$ = function(){ ... };

$ = function(){ ... };

$ = function(){ ... };
And enables you to use it like this:
$(...).foo().bar( ... );

$(...).foo( .... );

$(...).foo().baz( ... ).foo().bar( ... ).foo( ... );
As showed above, the method that acts as module, can also be used as function.
To avoid using it as module, the function must receive arguments.

How to use

Basic call
$.modularize( 'foo' );
If $ already exists, it will be used when $(...).foo(...) is called with arguments.
If $(...).foo(...) won't be used as method, then you don't need to declare it, just call the plugin before adding the sub-functions.

Providing a default method
$.modularize( 'foo', function(){ ... } );
The given function will be used when $(...).foo(...) is called with arguments.
This is a shortcut for declaring it, and then calling the plugin.

Nested calls
$.modularize( 'baz', null, $ );
This allows:
$(...).foo().baz().foobar( ... )
Instead of null, you could send the default method.
Before doing this call, make sure you created $

The 'this' (scope) of the methods, will always be pointing to the calling jQuery object, $(...).
The methods will be gathered on the first call to the function.
Thus, you can "modularize" before adding the sub-methods to the module, or after, it doesn't matter.

If you need to call the module and then add methods, or you just want the methods to be gathered each time, set
$ = true;
You can set this to true, call the methods, and then reset to false.




Anonymous said...

Please check out my comparison of jQuery.Modularize with other similar libraries.

Ariel Flesler said...

Very nice!!
Note that if you do define $.fn.textUtil, then you can call the plugin anytime you want, either before or after adding the methods.

Cheers, thanks for getting "into" the plugin :)

Rodrigo said...

Sample code:

$ = function(){};
$.modularize( 'foo' );
$ = function(){
console.log(' fired: '+this.html() +' bar');
$.modularize('bar', null, $ );
$ = function(){
console.log(' fired: ' + this.html() + ' foobar');
$('p').foo().bar(); // nothing happens
$('p').foo().bar(true); // log = fired: Paragraph bar
$('p').foo().bar().foobar(); //log = fired: Paragraph foobar

Do u know $('p').foo().bar(); isn't getting called?
if I pass any argument it works fine.

Ariel Flesler said...

Check the subsection called "Basic call". It states that functions that act as namespaces will not be actually called when called with 0 arguments.