domain-swap
domain-swap copied to clipboard
Code organization
So, I moved a bunch of code around, but I'm not really a JS guy.
Recommendations on design and code appreciated.
+@zachleat +@mattdsteele
Comma first var declarations—my eyes!!!! :p
@mattdsteele is probably more of an expert on this, but I try to structure my code such that none of my functions select DOM elements $('...')
or getElementById
(etc) inside of the function. This improves reusability and testability.
@zachleat is there an bast-practices style guide most JS devs use?
Ah, yes! https://github.com/rwldrn/idiomatic.js/ is a very popular one.
I like automating my standard code styling (stuff like trailing commas; avoiding global variables, etc), and JSHint is the way to go for that. Plus there's a Grunt plugin!
On a higher structural level, there's lots of ways to do it. I like the approach of defining DOM selectors in one place, makes modularization and testing easier as well. Kind of like how this code does it in the el
object.
You probably don't need a full RequireJS build for this, but you could get 80% of the benefit it provides by making your implicit dependencies explicit. The way I do that is wrap objects inside an IIFE and pass in the implied global variables as parameters. e.g. for options.js:
(function(DomainSet, Storage) {
//actual implementation
})(DomainSet, Storage);
Plus, if you ever wanted to make your code AMD compatible, this is basically how the code ends up looking.
+1
@mattdsteele thanks for the detailed answer (with links!)
I'll give it a shot at refactoring.