How to write a function as an event handler or a function that is called that takes an argument?

Here we use a function to use as an event handler using this :

 function validate() { if (this.val() == '') { return false; } } $(':input').change(validate); 

Here the same function is rewritten to accept an argument, so that I can explicitly call it:

 function validate(field) { if ($(field).val() == '') { return false; } } validate($('#customer_name')); 

How can I rewrite my validate function to make it suitable for use as an event handler as well as a standalone function to call?

+4
source share
2 answers

There are various ways to do this. One of them is to use the second, taking the field as a parameter and setting the event handler using a closure:

 function validate(field) { if ($(field).val() == '') { return false; } } // Use anonymous function to pass "this" to validate. $(':input').change(function() { validate(this); }); // Unchanged. validate($('#customer_name')); 

Another way is to use the first form and use apply () to call it with this overridden:

 function validate() { if ($(this).val() == '') { return false; } } // Unchanged. $(':input').change(validate); // Use `$(...)` as "this" when calling validate. validate.apply($('#customer_name')); 
+10
source

Use the fallback to this parameter if field not specified as an argument.

 function validate(field) { return $(field || this).val() != ''; } $(':input').change(validate); // using this context validate($('#someInput')); // using a parameter 
+5
source

All Articles