I have one page with two types of forms. I have a single form of type A at the top, and then I have 1 or more forms of type B below it.
I use the Module pattern + jQuery to wire up all the events on my forms, handle validation, ajax calls, etc.
Is this the preferred/valid way to define a singleton, as in Form A, and a reusable object class, as in Form B? They are very similar and I'm not sure if I need to be using object the prototype
property, new
, or a different pattern. Everything seems to work for me but I'm afraid I'm missing some key error.
Form A
javascript looks like this:
var MyProject.FormA = (function() {
var $_userEntry;
var $_domElementId;
var validate = function() {
if($_userEntry == 0) {
alert('Cannot enter 0!');
}
}
var processUserInput = function() {
$_userEntry = jQuery('inputfield', $_domElementId).val();
validate();
}
return {
initialize: function(domElementId) {
$_domElementId = domElementId;
jQuery($_domElementId).click(function() {
processUserInput();
}
}
}
})();
jQuery(document).ready(function() {
MyProject.FormA.initialize('#form-a');
});
Form B
, which is initialized one or many times, is defined like so:
var MyProject.FormB = function() {
var $_userEntry;
var $_domElement;
var validate = function() {
if($_userEntry == 0) {
alert('Cannot enter 0!');
}
}
var processUserInput = function() {
$_userEntry = jQuery('inputfield', $_domElement).val();
validate();
}
return {
initialize: function(domElement) {
$_domElement = domElement;
jQuery($_domElement).click(function() {
processUserInput();
}
}
}
};
jQuery(document).ready(function() {
jQuery(".form-b").each(function() {
MyProject.FormB().initialize(this);
});
});