Last active
December 21, 2017 14:05
-
-
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.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So for some reason, using
let
instead ofvar
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.