In our workplace we use simple ajax library for getting page data and submitting changes to the server. Sometimes we need to change the form’s field values. We know that fields can be of any type (dropdown, textbox, radio buttons, etc.) and one of the most annoying and tedious tasks was remembering each field’s ID so could do the manipulation. (The task can exceed a few days, so I had to keep the IDs in a text document). So I made this design pattern for easily working with the fields.
function FormFieldsManager() {
var FormMgr = {
txtGradeName: function (txt) {
if (txt) {
$('#txtGradeName').val(txt);
}
else {
return $('#txtGradeName').val();
}
},
txtGradeDesc: function (txt) {
if (txt) {
$('#txtGradeDesc').text(txt);
}
else {
return $('#txtGradeDesc').text();
}
},
ddStatus: function (txt) {
if (txt) {
if (isNaN(txt)) {
$("#ddStatus").val(txt);
}
else {
$("#ddStatus")[0].selectedIndex = txt;
}
}
else {
return $('#ddStatus :selected').val();//selected value: A
}
}
};
return FormMgr;
};
To use this function, I just call the method and I could navigate the form fields and get full JavaScript intellisense.
var form = FormFieldsManager();
form.txtGradeName('Software Developer');//to set the field value
form.txtGradeName();//to get the field value
So my questions are,
- What specific design pattern is this?
- What suggestions for improvement can you give?
P.S.: I like to call it jsPageObject.
5
This is superfluous since you will only need a once instance of that object ever because it has no state. You can simply do
var FormFieldsManager = {
txtGradeName: function (txt) {
...
},
txtGradeDesc: function (txt) {
...
},
ddStatus: function (txt) {
...
}
};
You can simply refer to that, no need to create it. This is simply namespacing static functions somewhere, dunno if that even has a name.
If it was an actual object with state, I guess an improvement would be to use prototype so it’s not as cast in concrete as it is now. You also
won’t create the function objects from scratch everytime but that only really matters when you create
100+ instances of something.
//This causes an error when you forgot to specify `new` as in `new FormFieldsManager()`
"use strict";
var method = FormFieldsManager.prototype;
function FormFieldsManager() {
this.state = "something";
}
method.txtGradeName = function (txt) {
...
};
method.txtGradeDesc = function (txt) {
...
};
method.ddStatus = function (txt) {
...
};
15