Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a function as both an event handler and a callable function that takes an argument?

Here's a function for use as an event handler that makes use of this:

function validate() {
  if (this.val() == '') {
    return false;
  }
}

$(':input').change(validate);

Here's the same function rewritten to take an argument, so that I can call it explicitly:

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 both an event handler, and as a standalone function for me to call?

like image 624
nfm Avatar asked Dec 07 '22 02:12

nfm


1 Answers

There are various ways to do this. One is to use the second one taking the field as a parameter and set 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 an overridden this:

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

// Unchanged.
$(':input').change(validate);

// Use `$(...)` as "this" when calling validate.
validate.apply($('#customer_name'));
like image 98
John Kugelman Avatar answered May 23 '23 01:05

John Kugelman