Getting and assigning values ββof form element in Javascript module template
I need to access all elements on a form with Module pattern
. In a nutshell, I want to avoid duplicate code and only use one module to organize.
How can I do this without calling the Anonymous function from the module:
Instead of writing like this: FormData.LastName()
I just want it to look like this:FormData.LastName;
Below is the example I tried:
'use strict';
FormData = (function() {
var formElement = document.forms.signup;
return {
LastName: function(){
return formElement.lName.value;
},
SendBtn: function(){
return formElement.submitSignupForm;
}
};
})();
Make calls to the module and get the internal values ββof the object to it without the need for Global
and exposure
.
FormData.SendBtn().addEventListener('click', function(e){
document.getElementById('result').innerHTML = FormData.LastName();
e.preventDefault();
}, false);
Another variation:
'use strict';
FormData = (function() {
var formElement = document.forms.signup;
var LName = function(input){
return input.lName.value;
};
var SendBtn = function(input){
return input.submitSignupForm;
};
return {
LastName: LName(formElement),
SendBtn: SendBtn(formElement)
};
})();
FormData.SendBtn.addEventListener('click', function(e){
document.getElementById('result').innerHTML = FormData.LastName;
e.preventDefault();
}, false);
source to share
Use Object.defineProperty
example: https://msdn.microsoft.com/en-us/library/dd548687%28v=vs.94%29.aspx
better docs: https://developer.mozilla.org/en-US/docs/Web/ JavaScript / Reference / Global_Objects / Object / defineProperties
var Mod = (function(){
var module, formElement;
module = {};
formElement = document.forms.signup;
Object.defineProperty(module, 'LastName', {
get: function () {
return formElement.lName.value;
},
writable: false,
enumerable: true,
configurable: true
});
return module;
})();
source to share