I'm trying to clean up my JavaScript code, so I can stop writing spaghetti code and have some more overall structure. I wanted to test my skills by writing a simple form validator. However, I got stuck already.
This is the code I have at the moment:
(function($, window, undefined) {
var Form = function($el) {
this.$el = $el;
this.fields = {};
this.prototype.validate = function() {
this.getFields();
}
this.prototype.getFields = function() {
console.log("getting fields");
}
return {
validate: this.validate
}
};
window.Form = Form;
})(jQuery, window);
$(function() {
var form = new Form('#form-newsletter');
form.validate();
});
A couple of questions about this.
I wrapped the Form variable in a self-executing function, passing in three parameters. jQuery, window and undefined to make sure it's always undefined. I'm not going to lie, this is how I learnt to do it and I'm not 100% sure why I do it this way. Is this bad practice or could I improve on this somehow? I then expose the Form variable by attaching it to the window.
Inside the Form var, I set some properties (is that how we call them?) and I have a couple of methods. I expose only the validate method in the return statement. Is this okay?
And then the part where I got stuck. I want validate() to be like an initialize function, which has the task of validating the form. Validate should call the getFields function to parse the form fields and put them into the fields object. However, I can't seem to get that working. It doesn't work when I call this.getFields(), this.prototype.getFields() or Form.getFields. Is this because the this inside this function is a different this than the Form object (correct wording here?)?. Should I put something like this.self = this at the start of the Form function?
I'm also wondering if it's okay to attach those methods to the prototype. Is there a reason not to do this?
I'm trying to learn; most books I read about JavaScript focus on the basics: a Dog class which inherits from a Mammal class. However, they don't really help me out with stuff like this, as far as I can tell. Are there any books, tutorials, screencasts out there to help me understand these concepts better?
EDIT:
Say I want to group my scripts under a common namespace: I could do
var MyStuff = {};
MyStuff.Utilities = { // stuff };
MyStuff.Form = function() { // stuff };
However, if I want to put these into separate files, like mystuff-form.js, mystuff-utilities.js, how would I go about it? Where do I declare the namespace var var MyStuff = {}? And after I do that, I can just attach my Form and Utilities to that, right? I can hardly make a MyStuff.js file with just var MyStuff = {}; window.MyStuff = MyStuff in it, can I?