简体   繁体   中英

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?

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'));

Use a fallback to this if field is not given as an argument.

function validate(field) {
    return $(field || this).val() != '';
}

$(':input').change(validate); // using this context
validate($('#someInput'));    // using a parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM