Simple boilerplate I use to start JavaScript projects.
-
-
Save nessthehero/4730750 to your computer and use it in GitHub Desktop.
// We're cooking with globals, so we use namespaces to avoid conflicts | |
var Namespace = Namespace || {}; | |
Namespace.Project = Namespace.Project || {}; | |
Namespace.Project.init = function () { | |
} | |
// Expecting jQuery, but you could easily change this to some other method of window ready or dom ready | |
$(function () { | |
// Cached selectors | |
Namespace.Project.$elm = {}; | |
// Arbitrary data (Comes after selectors so we can use them here) | |
Namespace.Project.data = {}; | |
Namespace.Project.init(); | |
}); |
@scottbert If you wrap everything in a closure, including your namespace, how would you go about working with multiple files?
In some cases, I create a "global" file that's included on all pages, containing helper methods, and functions I will need elsewhere.
I have been using this pattern lately.
var PROJECT = PROJECT || {};
(function(my){
/**
* Do some stuff
* @return {undefined}
*/
my.init = function() {
};
// DOM Ready, Execute
$(my.init);
}(PROJECT));
If you want to know whether undefined
has been fucked with, you can write:
if (undefined !== void 0) {
...
}
Similarly, you can set undefined for yourself with:
undefined = void 0;
Or the old classing as part of your IIFE:
(function (undefined) {
...
})();
@raganwald, had no clue about checking undefined with void 0
. I guess you learn something new everyday
I find AngularJS and RequireJS solves namespacing issues quite nicely
@mattgoucher I do that as well. I suppose you could take the solution from @scottbert and just leave the global namespace part uncommented so that it remains in the global namespace.
I like using browserify for this kind of thing. You have to do a static build step and async code loading is pretty much out of the question, but at least those require
s look nice. :)
@nessthehero, the main benefit is in case people set undefined to something other than "undefined". Undefined is something that should always be "undefined" no matter where you use it.
Some people (usually XSS) will purposely try to mess with code and insert values on a page that conflict with what you think you'll be using. This is why closures are so important, and also scope control of course.
If somewhere outside your closure, undefined gets set to "false" or "true" or whatever, now inside your closure you will have the correct value back.
It makes sure you don't have to think about your checks for undefined