JavaScript onKeyUp closures with timeout

2019-07-04 02:52发布

问题:

Im trying to assign an onKeyUp event to all inputs within a form, using closures. the array fields contains all the names of the fields that require the event assigned to them. The array ajaxFields contains the names of the fields (from the array fields) that requires ajax validation.

function createEvents(fields,ajaxFields) {
    for(var x=0;x<fields.length;x++) {

        $('input[name='+fields[x]+']').keyup(function(field) { 
        //assign an onKeyUp event
            return function() {
                //some code using variable 'field' and array 'ajaxFields'
        }(fields[x]));
    }
}

I would like the onKeyUp function to be executed a second after the user has finished typing in that field, insted of every time the key is up (onKeyUp). this would save up a lot of processing space, not to mention the ajax calls. So far im using this:

clearTimeout(timer);
timer = setTimeout('validate()' ,1000);

You might have noticed that the function validate() doesn't exist, and thats because I dont know how to wrap the closures inside a named function, and im not even sure if I should...

So how do I do that?

EDIT: here is a current fiddle

回答1:

You can (and should) pass functions to setTimeout instead of strings.

clearTimeout(timer);
timer = setTimeout(function(){
    // your code here
}, 1000);

So, in your keyup, try something like this:

$('input[name='+fields[x]+']').keyup(function(field) { 
//assign an onKeyUp event
    return function() {
        var that = this,
            $this = $(this);
        clearTimeout($this.data('timeout'));
        $this.data('timeout', setTimeout(function(){
            //some code using variable 'field' and array 'ajaxFields'
            // "this" will not be your element in here, make sure to use "that" (or "$this")
        }, 1000));
    };
}(fields[x]));

I save the timeout in $this.data, so that each element can have its own timeout, instead of using a global variable.

Updated Demo: http://jsfiddle.net/Z43Bq/3/



回答2:

This is what your code should look like:

var timer;

$(document).ready(function() {
    var fields = $('.field');
    var ajaxFields = $('.ajax-field');

    createEvents(fields, ajaxFields);
});

function createEvents(fields,ajaxFields) {
    // Use jQuery's "foreach" method
    $(fields).each(function(inx, field) {
        // Bind the listener here
        $(field).keyup(function(ev) {
            // Clear timeout if necessary
            if (timer != null) clearTimeout(timer);

            // Set the timeout
            timer = setTimeout(function() {
                // Your code should here

                console.log('Fields: ', fields, '\nAjax Fields: ', ajaxFields, '\nTHE field: ', field);
            }, 1000);
        });
    });
}

Also checkout the fiddle for the working code: http://jsfiddle.net/BLyhE/