tags:

views:

6133

answers:

5

Hi,

YUI has a nice way of creating a namespace for your methods etc. in javascript.

Does jQuery have anything similiar?

+4  A: 

jQuery has a bunch of plugins that extend the base functionality. There is this plugin for easy namespaces.

lpfavreau
+8  A: 

lpfavreau offers the solution to extend the jQuery object with your own methods (so that their functionality applies on the actual jQuery object context).

If you're looking to just namespace your code you can use the dollar symbol like this:

$.myNamespace = { .. };

or the "jQuery":

jQuery.myNamespace = { .. };

Be careful with the namespace you choose as this can overwrite existing jQuery methods (I'd suggest to first search in the jQuery code so that you don't).

You can follow this link: http://www.zachleat.com/web/2007/08/28/namespacing-outside-of-the-yahoo-namespace/

See how easy it is to create your own function to replicate what YUI does:

// include jQuery first.
jQuery.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

// definition
jQuery.namespace( 'jQuery.debug' );
jQuery.debug.test1 = function()
{
    alert( 'test1 function' );
};
jQuery.debug.test2 = function()
{
    alert( 'test2 function' );
};
// usage
jQuery.debug.test1();
jQuery.debug.test2();
Luca Matteis
+1  A: 

Depending on what you're trying to do, jQuery's plugin architecture may be what you're looking for:

$.fn.myPlugin = function() {
  return $(this).each(function() {
    // do stuff
  });
};

or ...

$.fn.myPlugin = function() {
  var myNamespace = {
    // your stuff
  };
};

really it depends on what you're trying to do.

http://docs.jquery.com/Plugins/Authoring

rmurphey
A: 

jquery.namespace above has a memory leak, the second for loop causes a circular reference.

kchea
A: 
var ANAM = new Object(); // hack to create a namespace

ANAM.Gallery = function() { // creates a singleton
    // private variables
    var node;
    var template = '<div class="polaroid"><div class="bd"><a href="Gallery.php"><img src="{path}" width="{width}" height="{height}" alt="" /></a><div class="caption" style="width: 370px;">{caption}</div></div></div><div class="clear" style="height: 0.5em;">&nbsp;</div>';
    // private methods
    function setAjaxErrorHandler(_node) {
        node = _node;
        $(node).ajaxError(function(event, request, settings) {
            $(this).append('Error ' + request.status + ' requesting ' + settings.url).css('background-color', 'yellow');
        });
    }
    function addImage(image) {
        $(node).append(template.replace('{path}', image.path).replace('{width}', image.width).replace('{height}', image.height).replace('{caption}', image.caption));
    }
    // public interface
    return {
        // public properties
        Author: 'David Balmer',
        Template: template, // expose a private variable
        // public methods
        GetImages: function(oConfig) {
            setAjaxErrorHandler(oConfig.node);
            $.ajax({
                url: 'ajax/gallery.php',
                dataType: 'json',
                data: {'target': oConfig.target},
                success: function(data) {
                    $.each(data, function(index, image) {
                        addImage(image);
                    });
                }
            });
        }
    };
}(); // the parens here cause the anonymous function to execute and return

ANAM.Gallery.GetImages({'node': '#gallery', 'target': 'homepage'});

<div id="gallery"></div>
David Balmer