Building your own jQuery extensions

Release 1.2 - ...

jQuery provides an extension framework. Extensions can be added as 'static' methods, and as jQuery selector methods.

Static methods

Let's say we want to add a custom set of static methods to jQuery, under a myNamespace namespace:

Javascript CopyCode image Copy Code
// create static jQuery methods in namespace nested under scf.
$j.myNameSpace = {
 sub1: {
  test: function(data){
   alert('Static test method: ' + data);
  }
 },
 
 sub2: {
  anotherOne: function(data){
   return data.toUpperCase();
  }
 }
};

Note that when multiple scripts extend an object, they will have to test whether the object is already extended.

Consider these two snippets:

Javascript CopyCode image Copy Code
// create static jQuery methods in namespace nested under scf.
$j.myNameSpace = {
 sub1: {
  test: function(data){
   alert('Static test method: ' + data);
  }
 }
Javascript CopyCode image Copy Code
$j.myNameSpace = {
 sub2: {
  anotherOne: function(data){
   return data.toUpperCase();
  }
 }
};

The result of this is that $j.myNameSpace.sub1 will no longer exist!

A safer approach would be to test for the main namespace first:

Javascript CopyCode image Copy Code
$j.myNameSpace = $j.myNameSpace || {};
$j.myNameSpace.sub1: {
  test: function(data){
   alert('Static test method: ' + data);
  }
}

Now, do the same for the next extension:

Javascript CopyCode image Copy Code
$j.myNameSpace = $j.myNameSpace || {};
$j.myNameSpace.sub2: {
  anotherOne: function(data){
   return data.toUpperCase();
  }
};

Now, we can use the new methods:

Javascript CopyCode image Copy Code
$j.myNameSpace.sub1.test('Hello World!');

jQuery Selector Methods

Many, many jQuery addins are available out there. The problem they all share however, is that jQuery doesn't have native namespace support for selector methods. All methods added by jQuery addins are added to the main jQuery.fn object.

To avoid name collisions Scf provides an adapted version of Gilberto Saravia's namespace addin:

Javascript CopyCode image Copy Code
// add jQuery selector methods in namespace nested under scf.
$j.namespace("myNamespace", {
 doIt: function(){
  return $j(this).each(
   function(){
    alert($j(this).get(0).tagName + ' is tested!');
   }
  );
 }
});
 

Now, let's test the newly created jQuery selector method:

Javascript CopyCode image Copy Code
$j("div#main").myNamespace.doIt();