I took a stab at making it a little bit simpler:
function package(ns) {
ns = ns.split('.');
var cur = window, i;
while ( i = ns.shift() ) {
if ( !cur[i] ) cur[i] = {};
cur = cur[i];
}
}
so, at the top of your code just add:
package("foo.bar.baz");
and it makes sure that that namespace exists.
While I don't think this belongs in jQuery's core - adding this in to
a central OO/inheritance plugin might be a good idea.
--John
On 11/16/06, Rich Manalang <[EMAIL PROTECTED]> wrote:
> Hi all. With a lot of developers writing javascript these days, it's easy
> to write something that collides with someone else's code. I like Dojo's
> and YUI's approach to namespaced code. So, I decided to create a plugin for
> jQuery that allows you to create namespaced objects... it's actually a
> transposed version of YUI's namespace function:
>
> jQuery.namespace = function(ns) {
> if (!ns || !ns.length) { return null }
> var levels = ns.split(".");
> if (eval('typeof '+levels[0]+'=="undefined"')) {
> eval(levels[0]+'={}');
> }
> var nsobj = eval(levels[0]);
> for (var i=1; i<levels.length; i++) {
> nsobj[levels[i]] = nsobj[levels[i]] || {};
> nsobj = nsobj[levels[i]];
> }
> return nsobj;
> };
>
> Feed it a namespace:
>
> $.namespace("org.jquery.utils")
>
> Then start using your new namespaced object:
>
> org.jquery.utils.HelloWorld = function() {alert('hi')}
>
> This would actually be a nice feature to add to the base jQuery library...
> any thoughts on that?
>
> Rich
>
> _______________________________________________
> jQuery mailing list
> [email protected]
> http://jquery.com/discuss/
>
>
>
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/