How to run a function once when binding to multiple events that all trigger in Javascript?

前端 未结 5 1095
失恋的感觉
失恋的感觉 2020-12-19 20:23

I have a search input that listens to keyup and change to trigger an update of a listview via Ajax.

Looks like this:

input.on         


        
5条回答
  •  难免孤独
    2020-12-19 20:30

    I would try to set up a value-checking function like this:

    var $inputIntance = $("#path-to-your-input");
    var lastInputValue;
    
    function checkInputValue () {
        var newValue = $inputIntance.val();
        if (newValue != lastInputValue) {
            // make your AJAX call here
            lastInputValue = newValue;
            el = $inputIntance.closest('ul');
            widget[func](dyn, el, lib_template, locale, lastInputValue, "update");
        }
    }
    

    and then then fire this checks by any user-action event you like:

    $inputIntance.on('keyup change', function(e) {
        checkInputValue();
    }
    

    or like this

    $inputIntance.on('keyup change', checkInputValue );
    

    UPDATE: there might be the case when you have to limit the number of AJAX requests per time. I added time control functionality to my previous code. You can find the code below and try it live here in JSFiddle.

    $(document).ready(function () {
        var $inputIntance = $("#test-input");
        var lastInputValue;
        var valueCheckTimer;
        var MIN_TIME_BETWEEN_REQUESTS = 100; //100ms
        var lastCheckWasAt = 0;
    
        function checkInputValue () {
            lastCheckWasAt = getTimeStamp();
            var newValue = $inputIntance.val();
            if (newValue != lastInputValue) {
                // make your AJAX call here
                lastInputValue = newValue;
                $("#output").append("

    AJAX request on " + getTimeStamp() + "

    "); //el = $inputIntance.closest('ul'); //widget[func](dyn, el, lib_template, locale, lastInputValue, "update"); } } function getTimeStamp () { return (new Date()).getTime(); } function checkInputValueScheduled() { if (valueCheckTimer) { // check is already planned: it will be performed in MIN_TIME_BETWEEN_REQUESTS return; } else { // no checks planned if ((getTimeStamp() - lastCheckWasAt) > MIN_TIME_BETWEEN_REQUESTS) { // check was more than MIN_TIME_BETWEEN_REQUESTS ago checkInputValue(); } else { // check was not so much time ago - schedule new check in MIN_TIME_BETWEEN_REQUESTS valueCheckTimer = window.setTimeout( function () { valueCheckTimer = null; checkInputValue(); }, MIN_TIME_BETWEEN_REQUESTS ); } } } $inputIntance.bind('keyup change', function(e) { $("#output").append("

    input event captured

    "); checkInputValueScheduled(); }); });

提交回复
热议问题