Created
August 14, 2012 00:40
-
-
Save rogeruiz/3345181 to your computer and use it in GitHub Desktop.
Organizing JavaScript with Namespaces and Function Prototypes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* ============================================================================= | |
| @title Organizing JavaScript with Namespaces and Function Prototypes | |
| @author by Jimmy Cuadra | |
| @source http://jimmycuadra.com/posts/organizing-javascript-with-namespaces-and-function-prototypes | |
| */ | |
| // file : main.js | |
| if (typeof MTNT == 'undefined'){ | |
| MTNT = {}; | |
| } | |
| // file : mtnt.form-validator.js | |
| MTNT.FormValidator = function(){ | |
| // code for validation goes here. | |
| }; | |
| // You can instantiate a new module by using: | |
| // new MTNT.FormValidator(); | |
| // ============================================================================= | |
| // file : mtnt.form-validator.js | |
| MTNT.FormValidator = function(myProperty, form){ | |
| // initialize some variables | |
| this.myProperty = myProperty; | |
| this.form = form; | |
| // ... | |
| // call a function to validate the form data | |
| this.form.submit(this.validate); // 'submit' is jQuery's submit method | |
| }; | |
| MTNT.FormValidator.prototype.validate = function(){ | |
| // validate the form data | |
| // ... | |
| }; | |
| // ============================================================================= | |
| // Function.prototype.bind(); | |
| if (typeof Function.prototype.bind == 'undefined'){ | |
| Function.prototype.bind = function(){ | |
| var __method, args, object; | |
| __method = this; | |
| args = Array.prototype.slice.call(arguments); | |
| object = args.shift(); | |
| return function(){ | |
| var local_args = args.concat(Array.prototype.slice.call(arguments)); | |
| if (this !== window){ | |
| local_args.push(this); | |
| } | |
| return __method.apply(object, local_args); | |
| }; | |
| }; | |
| } | |
| // ============================================================================= | |
| // file : mtnt.form-validator.js | |
| MTNT.FormValidator = function(myProperty, form){ | |
| // initialize some variables | |
| this.myProperty = myProperty; | |
| this.form = form; | |
| // ... | |
| // call a function to validate the form data | |
| this.form.submit(this.validate.bind(this)); | |
| }; | |
| MTNT.FormValidator.prototype.validate = function(event, form){ | |
| // 'event' is the event object that is normally passed into event handlers by jQuery | |
| // 'form' is the original value of 'this' that jQuery would have set | |
| // validate the form data | |
| // ... | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment