Last week, I gave a presentation at the Columbus Ruby Brigade meeting about metaprogramming JavaScript. Although I posted that presentation here, the slides were short on text, so I thought it would be more helpful if I wrote a series of tutorials to discuss these concepts. Also, I want to take my example a bit further with more extensions and refactoring.
But before we dive into what metaprogramming is, why it is important, and how we can bring it to life in JavaScript, let’s start with an example that we can build on throughout the tutorial: Say we’ve got a really basic form with select boxes for country and state, and we have a requirement to only show the state when the selected country is “United States”.
This code works just fine, and there is certainly nothing wrong with it for such a simple requirement. Unfortunately, things get hairy as requirements change. Let’s see how our code scales when we want to do the following: