views:

61

answers:

2

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?

+10  A: 

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'));
John Kugelman
+1 for apply(). It's the nicer, more idiomatic alternative, IMHO.
Tomalak
PS: There's an error in your second code sample. I think it should be `$(this)` in the function body.
Tomalak
+5  A: 

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
Anurag