For example, there is such an object

Project.Module.Contact = { Init : function() { this.Validate(); }, Rules : { // Code }, ContactForm : $('#contact-form'), ResponseCont : $('#response-cont'), Validate : function() { this.ContactForm.validate(this.Rules); this.ContactForm.submit(this.FormSubmit); }, FormSubmit : function(e) { e.preventDefault(); if (!$(this).valid()) return; $.post(this.action, $(this).serialize(), this.AjaxResponse); }, AjaxResponse : function(response) { // Code } } 

Of course, it will not work, because in the "FormSubmit" this will give us the form itself and this: this.AjaxResponse will not work, you can contact so Project.Module.Contact.AjaxResponse will work this way, but I do not think that write such long lines well, what can you do? how to apply differently?

    2 answers 2

    one option to use bind

     Validate : function() { this.ContactForm.validate(this.Rules.bind(this)); this.ContactForm.submit(this.FormSubmit.bind(this)); }, 

    But then you have to change the FormSubmit , because now this method expects a jQuery object instead of the main object.

    Like so

     FormSubmit : function(e) { e.preventDefault(); if (!this.ContactForm.valid()) return; $.post(this.ContactForm.prop('action'), this.ContactForm.serialize(), this.AjaxResponse); }, 

      Alternatively, you can declare a module through a closure — this is the standard way to declare a module.

      Unfortunately, many IDE still do not understand it.

       Project.Module.Contact = function() { var module = { // ... } return module; }() 

      Here a function is created that is immediately called. This function creates a module object and returns it immediately. What is it done for? And in order to get additional scope.

      So, inside the function, the module is pre-placed in the local variable module - and therefore, it can be obtained through this variable:

       FormSubmit : function(e) { e.preventDefault(); if (!$(this).valid()) return; $.post(this.action, $(this).serialize(), module.AjaxResponse); }, 

      Also, such a trick allows introducing closed variables and module functions that are inaccessible from the outside - which makes it possible to reduce the code connectivity and avoid problems with excessive dependencies of modules from each other.

      For example, the FormSubmit and AjaxResponse clearly only needed for internal use, which means there is nothing for them to do in the module object:

       Project.Module.Contact = function() { var module = { // ... Validate : function() { module.ContactForm.validate(module.Rules); module.ContactForm.submit(FormSubmit); }, } return module; function FormSubmit (e) { e.preventDefault(); if (!$(this).valid()) return; $.post(this.action, $(this).serialize(), AjaxResponse); } function AjaxResponse (response) { // Code } }()