Writing better javascript – Part 7
The options argument
This practice is something that came to me after I ran into some flexibility issues with the JavaScript components I was creating. If you have been following this series, you might have noticed that I use the module pattern to create my JavaScript classes. As our JavaScript library started growing in size and the components I was creating was getting more complex, there was a need to be able to allow for ways to configure them wherever possible. Coming from the .NET universe, I started doing what I would have done if I was writing C# classes. I started modifying the constructor for the classes and started adding the different configurations points as arguments to the constructor like below.
var FormHelper = function(formID, cssClass, validationRules, submitHandler, cancelHandler/*constructor arguments defined here*/) {
//Declare private variables here
//Declare private methods here
return {
//Declare public properties here
//Declare public methods here
};
};
The class just started off with ‘formID’ as the only argument. But as I started adding more extensibility points, I had started adding more arguments seen above like ‘cssClass’, ‘validationRules’, ’submitHandler’ and ‘cancelHandler’ etc. These arguments started getting out of hand as I needed more extensibility points. And since JavaScript is JavaScript, I had to pass in the correct arguments in the exact index at which the argument is expected. Not a real good way of doing things. Thinking about it a little more and dwelling on it for a while I realized that the solutions was just to take an options argument that contains all the extensibility points as properties on it. See the changes below
var FormHelper = function(formID, options/*constructor arguments defined here*/) {
//Declare private variables here
//Declare private methods here
return {
//Declare public properties here
//Declare public methods here
};
};var formOptions = {
cssClass: “someClass”,
validationRules: rules,
submitHandler: handleSubmit,
cancelHandler: handleCancel
};var test = new FormHelper(”LatLongForm”, formOptions);
Doing it that was much cleaner. And didn’t have to change the definition of the constructor every time I wanted to add more extensibility points. Once I started writing my classes that way, I started noticing that the above pattern was used all the major JavaScript libraries. Probably should have seen the reason behind it earlier when I was using those libraries. But, now I know and am probably a better developer for it. But you don’t have to make that mistake and learn from my experience and follow this pattern from the get go.
Follow Me
Contact me