Using Underscore's _.debounce() method

一曲冷凌霜 提交于 2021-02-07 12:33:16

问题


I'm trying to use UnderscoreJS and it's _.debounce() method to stop a callback function for firing repeatingly on keyup event. I'm doing that because each time you start typing, an AJAX call will be fired up so it would be quite expensive to make a call for each character you type (:

This is how I'm using the method :

onTypeEvents : function(selector, callback) {
        return $(selector).on('keyup', function(event){

            var that = $(this).val().trim();

            switch(event.keyCode) {
                case 8:
                    if(that !== '') {
                        if(that.length >= 2) {
                            return _.debounce(function() { callback.apply(that, [ that ]) }, 150);
                        } else {
                            return _.debounce(function() { callback.apply(null, [ null ]) }, 150);
                        };
                    };
                    break;
                case 9:
                    break;
                case 13:
                    break;
                case 27:
                    break;
                case 37:
                    break;
                case 38:
                    break;
                case 39:
                    break;
                case 40:
                    break;
                default:
                    if(that !== '') {
                        if(that.length >= 2) {
                            return _.debounce(function() { callback.apply(that, [ that ]) }, 150);
                        } else {
                            return _.debounce(function() { callback.apply(null, [ null ]) }, 150);
                        };
                    };
                    break;
            };

            event.preventDefault();
            event.stopPropagation();
        });
    },

But apparently it doesn't work because nothing is firing up anymore, but if I remove the method my code works just fine (: So what could be going wrong in there ? Am I doing it wrong or am I missing something ?


回答1:


The idea is to debounce the keyup callback itself. That way your code only reacts to the last key your user typed before he stopped typing. Something like:

$(selector).on('keyup', _.debounce(function (e) {
  switch (e.keyCode) {
    /* your code */
  }
}, 500));


来源:https://stackoverflow.com/questions/13158708/using-underscores-debounce-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!