How could I improve this code so that I didn't need to place all code inside initAll()?
I have some form handling stuff, and I want to refactor that to OOP. This is the first thing I need to be more sure about.
Code:
/* Handling forms with object oriented programming. */
/* Wait for the DOM the be ready. */
window.onload = initAll;
function initAll() {
var FormValidator = { // {{{
msg: document.forms['contact'].msg,
}; // }}}
//console.log(FormValidator.msg);
/* Inserts 'value' into the textarea. */
FormValidator.msg.value = 'Hello world, from JavaScript!';
}
/* vim:set foldmethod=marker foldmarker={{{,}}}: */
There isn't much code to go on, but if your goal is to encapsulate the functions and variables (avoiding global scope), then doing it all in the initAll function is fine.
To be a little cleaner you could also just assign the function directly to the window.onload event and drop the name:
Code:
/* Handling forms with object oriented programming. */
/* Wait for the DOM the be ready. */
window.onload = function()
{
var FormValidator = { // {{{
msg : document.forms['contact'].msg
}; // }}}
//console.log(FormValidator.msg);
/* Inserts 'value' into the textarea. */
FormValidator.msg.value = 'Hello world, from JavaScript!';
};
/* vim:set foldmethod=marker foldmarker={{{,}}}: */
var myObj = {
/* Gets the <textarea> element. */
my_element: document.forms['contact'].msg
}
/* Places a (default) text inside the <textarea>. */
myObj.my_element.value = 'Hello, world';
Is there a way to load it when the DOM is ready, but without placing all the code inside a function attached to the "onload" event? Otherwise I will always have to place all my code inside a single function... Bear with me, please.
Bookmarks