Skip to content

Instantly share code, notes, and snippets.

@eiwi1101
Last active December 21, 2017 14:05
Show Gist options
  • Save eiwi1101/e492b7d04003d17d0dcfeb456eb73fdb to your computer and use it in GitHub Desktop.
Save eiwi1101/e492b7d04003d17d0dcfeb456eb73fdb to your computer and use it in GitHub Desktop.
It's like `mkdir -p` but for Javascript objects! (Probably an anti-pattern.)
// I often do stuff like (coffeescript):
//
// class @Forms.Select extends React.Component
//
// Which, often requires an ugly @Forms ||= {} somewhere, or this will
// explode. Now, I know there's better ways to do this, and CommonJS has
// its nifty resource stuff, but I am old and stuck in my ways and stuff.
//
// With this snippet (if you're in rails, you can include it in application.js
// before your components dir), you can write (again, coffee):
//
// namespace 'Forms'
// class @Forms.Select extends React.Component
//
// It will also take a path and call itself recursively. The return value, if
// for whatever reason you want to use it, is a reference to the LAST object
// declared in the namespace.
//
// namespace 'User.Account'
// class @User.Account.Menu extends React.Component
//
// Caveat(s):
//
// 1) A Ruby dev wrote this. What even IS Javascript?!
// 2) If anything in the class path isn't an object, this will probably puke
// 3) I'm not responsible for bad habits that result from this pattern.
// 4) You know, this can easily be used on other objects, consider it mkdir -p
// foo = {}
// namespace('bar.baz.qux', foo) //=> { foo: { bar: { baz: { qux {} } } }
//
window.namespace = function(ns_path, parent) {
var spaces, final, current;
if(!ns_path) return;
if(!parent) parent = window;
if(ns_path.unshift) {
spaces = ns_path;
} else {
spaces = ns_path.split('.');
}
current = spaces.shift();
if(typeof window[current] === 'undefined') {
final = parent[current] = {};
}
if(spaces.length > 0) {
return namespace(spaces, parent[current]);
} else {
return final;
}
};
@eiwi1101
Copy link
Author

So for some reason, using let instead of var totally broke all the javascripts in production.

Specifically, I was getting "Undefined variable: $" issues, which on further eval turned out that, eh... nothing was loading? What?

Explain.

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