In our workplace we use simple ajax library for getting page data and submitting
ID: 646691 • Letter: I
Question
In our workplace we use simple ajax library for getting page data and submitting changes to server ,on certain occasions we do need to change the forms fields values ,now we know that fields can be of any type (dropdown , textbox and radiobuttons etc) and one of the most annoying and tedious task I find was remembering various fields id so could do the manipulation (the task can exceed for few days,so I had to keep the ids in notepad) ,then I made this design pattern for easy 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;
};
In order to use that function,I just call the method and I could navigate the form fields and I 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 suggestion for improvement you guys can give?
PS: I like to call it jsPageObject :)
Explanation / Answer
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) {
...
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.