Skip to content

Instantly share code, notes, and snippets.

@nzakas
Created December 6, 2011 19:14
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nzakas/1439504 to your computer and use it in GitHub Desktop.
Save nzakas/1439504 to your computer and use it in GitHub Desktop.
A single global with a namespace method
//BSD Licensed
var YourGlobal = {
namespace: function(ns){
var parts = ns.split("."),
object = this,
i, len;
for (i=0, len=parts.length; i < len; i++) {
if (!object[parts[i]]) {
object[parts[i]] = {};
}
object = object[parts[i]];
}
return object;
}
};
//usage
YourGlobal.namespace("foo.bar");
YourGlobal.foo.bar.message = "Hello world!";
YourGlobal.namespace("foo").baz = true;
@zachleat
Copy link

zachleat commented Dec 6, 2011

Looks like YUI :)

@nzakas
Copy link
Author

nzakas commented Dec 6, 2011

Indeed, however, written completely from scratch without looking at YUI (or any other) code. It's sometimes fun to see if you can create something by just understanding the concept and not looking at example code.

@jaguire
Copy link

jaguire commented Dec 6, 2011

Great minds think alike! https://gist.github.com/1409388

@millermedeiros
Copy link

or you could use the AMD module format and forget about globals/namespaces.. #winning

@ghinch
Copy link

ghinch commented Dec 6, 2011

AMD is retarded. My callback method gets a param passed for each module I use? Most applications I develop use dozens of modules at a time. No thanks.

"Namespaces are one honking great idea -- let's do more of those!"
-The Zen of Python

@jaguire
Copy link

jaguire commented Dec 6, 2011

@millermedeiros I actually looked into using require. The problem with require is it causes a browser request for each module. Not a huge deal but large projects will eventually have many modules/classes. I didn't want to create module bundles either. Mine was designed with the expectation that all modules will be bundled/minified into one file before deployment. I was also going for simplicity and this is extremely simple.

@millermedeiros
Copy link

@jaredmcguire I've been coding projects broken up into 100-200+ modules (individual JS files) during development and 1-10 modules for production - most projects are combined into a single file, others I load some parts on-demand - just need to use RequireJS optimizer to combine your modules before deploy, good development experience (can simply refresh the browser to see the updates, add breakpoints, etc..) and optimal performance for production code.

@ghinch AMD isn't retarded, it provides a sane way of keeping dependencies in sync and favor good practices like splitting your code into smaller specialized objects (single responsibility principle), automate the concatenation/build process (avoiding ordering errors / human errors), reduces the amount of globals, etc... It is also flexible enough to avoid problems with circular dependencies and has support for plugins which can be used to load more than just JS files (reducing the need of multiple nested callbacks and simplifying the logic in many cases). - Understand the tools before making "critics", calling it retard isn't what I would call constructive criticism. - A good link for you: Four stages of Competence..

If your module has too many dependencies than it is probably doing more than it should (it is a "code smell")... - my modules usually have less than 5 dependencies - always remember about the single responsibility principle...

PS: I used pseudo-namespaces for a long-time and can't see myself going back to this approach unless I really need it or the project is so simple that wouldn't benefit from AMD... my comment wasn't to start a flame-war but to show another option that is being adopted by many people (dojo, mootools, jquery...) and which I think should be the recommended approach.

@jaguire
Copy link

jaguire commented Dec 6, 2011

@millermedeiros I agree with you. I like require and plan on using it in some projects.

@ryanflorence
Copy link

Anybody who thinks AMD is about loading files needs to either 1) stop talking about AMD or 2) use it, read about the r.js optimizer, and then form an opinion.

This is a neat function, and almost identical to some of my object utilities at https://gist.github.com/1184675.

I prefer AMD so that the location of my modules map to the file system with no chance of overwriting, and each module declares its dependencies or else it's broken. It is way easier for another dev to know where to find my code and not break it.

This gist's pattern still leaves app organization wide open.

Sorry, I'm getting all AMD defensive on a well-intentioned, and valuable gist. Thanks nzakas!

@ghinch
Copy link

ghinch commented Dec 6, 2011

@millermedeiros If anything the single responsibility principle exacerbates the issue. I'm a huge fan of YUI and their Loader mechanism, so I'll use that as a reference for what I like. The YUI Plugin model allows just that, single responsibility. You can define a single base class, and then any number of plugins to augment that base with additional functionality. In a project I'm on now, we use it to add a lot of different functionality to tables throughout the app (I think we have 4 different tables, and then around 20 plugins that get mixed around to augment them). The most functional table has about 15 plugins on it. At some point you have to get down to implementation time, and load all those modules (each plugin is a module, and so is the table). With namespacing, I can attach them all to a single sandboxed global which is passed in to the implementation. I just list them all once in the requirements. Under the AMD spec, I would list all the required modules, and then also in the execution method list them again as arguments. Retarded. And I use that word not to make constructive criticism, but to offend people, so maybe they will pay attention for once. AMD seem to me to have come out of a combination of intellectual idealism as well as the limited practical development experience of the greater Javascript community (see jQuery's popularity). I sincerely hope it doesn't become a standard without some serious revision.

@millermedeiros
Copy link

@ghinch so you are really at the 1st stage, there is nothing that I can do until you realize that - you don't know that you don't know - but since more people will read this gist, it is worth replying to your last comment.

There are many ways to not list all dependencies all the time, there are things like dependency injection, the simplified commonjs wrapper format, or heck, you could even create your own modules to act like packages/namespaces and/or extend a single module (like dojo does). AMD is just a "authoring/transport format" for the code, good/bad structure can be applied no matter what is the format, be it YUI, AMD, CJS, etc.. Good tools aren't a replacement for good architecture.

"AMD seem to me to have come out of a combination of intellectual idealism as well as the limited practical development experience of the greater Javascript community (see jQuery's popularity)..."

read the why AMD page before saying this kind of stuff, you clearly don't know what you are talking about...

Don't be so biased and rude... It may not be the "right tool" for your coding style but it may be the "best option" to many people. - that's why there are so many different libraries/frameworks that does the "same" thing with a different style, they are simply targeted to a different audience, if you are not the target than don't use it, but try to understand it before making any assumptions, you may learn something in the way or even find out that your preconceptions were wrong.

PS: I don't want to keep discussing this subject here, read the links and if you have any real question send it to the RequireJS list, the AMD format is a standard and is being discussed at the AMD implement list - only constructive criticism is welcome. Cheers.

@medikoo
Copy link

medikoo commented Dec 7, 2011

@nzakas I would also say that namespaces like that one are "old school" now, and using modules e.g. NodeJS style is much more worth it.
I switched to that about half year ago and don't look back.

However I wouldn't point AMD as right solution, AMD concept is ok, where you think of module as of functionality, so one module is already a quite large codebase. On programming level modules are much more fine grain and loading tens (many times hundreds) of such modules with AMD is total overkill.
I write modules Node.js style pack them for browser with modules webmake and then if I need to separate some functionalities (packs of modules) I would use some kind of loader, not sure if AMD, as it seems too big (in terms of API) for such simple needs. If someone is interested I coined better my experiences here: JavaScript Modules

@nzakas
Copy link
Author

nzakas commented Dec 7, 2011

@medikoo - I don't see modules and namespaces as mutually exclusive.

@medikoo
Copy link

medikoo commented Dec 7, 2011

@nzakas they're not, I was rather referring to style of building one big namespace (of namespaces) in one global variable, with Node.js style modules you can build complex applications and don't use global variables at all, also you don't have to nest namespaces as it's in your example.

@nzakas
Copy link
Author

nzakas commented Dec 7, 2011

@medikoo - I'm not sure why you're making so many assumptions about my intentions. Namespacing is still a useful technique, I just wanted to share this code. Use it however you want, with modules, without modules, with Node.js, with a browser...it really doesn't matter to me. This isn't a debate, it's just sharing some code.

@medikoo
Copy link

medikoo commented Dec 7, 2011

@nzakas I thought you're intention was to show new function that may help with client-side modules organization. I just wanted to shed a light on new techniques that developed recently and will be part of standard in a future (Harmony modules), that's it. If I misunderstood your point, sorry about that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment