lodash debounce not working in anonymous function

后端 未结 5 1357
忘了有多久
忘了有多久 2020-12-08 18:08

Hello I cannot seem to figure out why the debounce function works as expected when passed directly to a keyup event; but it does not work if I wrap it inside an anonymous fu

5条回答
  •  清歌不尽
    2020-12-08 18:54

    As Palpatim explained, the reason lies in the fact that _.debouce(...) returns a function, which when invoked does its magic.

    Therefore in your #anonFunction example, you have a key listener, which when invoked does nothing but return a function to the invoker, which does nothing with the return values from the event listener.

    This is a snippet of the _.debounce(...) definition:

    _.debounce
    function (func, wait, immediate) {
        var timeout;
        return function() {
          var context = this, args = arguments;
          var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
          if (immediate && !timeout) func.apply(context, args);
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
        };
      } 
    

    Your key event listener must invoke the returned function from _.debounce(...), or you can do as in your non-anonymous example and use the returned function from the _.debounce(...) call as your event listener.

提交回复
热议问题