The jquery.namespace.js plugin

The jquery.namespace.js plugin

jquery.namespace.js

Use this plugin when you want to create a plugin that is in a namespace not immediately attached to the $.fn namespace.

For example, let's say you work for acme.com and all plugins must be in the reverse-domain namespace of com.acme.

Simply writing $.fn.com.acme.myplugin = function(){ ... } will not work for a number of reasons.

  1. The intermediate objects com and com.acme don't yet exist.
  2. Even if you created them, calling $('p').com.acme.myplugin() still will not work because the value of "this" will not be set to the $.fn prototype. Instead, it will be set to the com.acme object which means you will not have access to the elements specified by the $('p') selector.

To help you do this, the jquery.namespace.js plugin adds two functions to the $.fn object: the $.fn.namespace function and the $.fn.call function.

The $.fn.namespace function creates a namespace from a dotted-name, creating all intermediate objects as required. The namespace is created on the $.fn object. When used in a plugin, all components except for the plugin name should be provided as the name argument.

The $.fn.call function takes a fully-qualified method name as its first argument followed by additional arguments to be passed to the method.

Additional Benefits

There is a side benefit of using the $.fn.call method. You no longer need to look at the first argument to your plugin method, determine that it is a string (i.e., the command name), and then find the correct method.

Assume you have a method called $.fn.com.acme.myplugin.mymethod. Calling this using the $('p').call('com.acme.myplugin.mymethod', args) will do the trick. The original jQuery this pointer referring to the wrapped element set will be correctly maintained when invoking mymethod.

Attached Files

jquery.namespace.js
The actual plugin.
jquery.namespace.html
A sample HTML file that shows how to write and call a plugin using the jquery.namespace.js plugin.

Credits

The namespace function was originally written by Mark A. Ziesemer