开发者

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() == '') {
  开发者_如何学JAVA  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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜