Conditional debounce, depending on event.keyCode

邮差的信 提交于 2019-12-11 05:09:16

问题


I have a search field that takes user input and makes ajax requests using a debounced event listener.

html:

<input id="search" type="text"></input>

javascript:

function makeRequest() {
  // make ajax request, do things with the information
}

$('#search').on('keypress', _.debounce(makeRequest, 200));

I need the event listener to not use the debounced ajax function on arrow up and down, that is event.keyCode === 38 or event.keyCode === 40

Is there a way to apply the advice from this question to my problem?


回答1:


Make sure you save the results and only call the function, creating the function on every keypress creates an unnecessary overhead.

var debounced = _.debounce(makeRequest, 200);
$('#search').on('keypress', function(event) {
    // just exit if it's an up or down arrow
    if (event.which === 38 || event.which === 40) return;
    debounced();
});



回答2:


You just need to handle the keypress event in a different manner, where you can see the event properties.

Try this instead...

$('#search').on('keypress', function(event) {

    // just exit if it's an up or down arrow
    if (event.which === 38 || event.which === 40) return;

    // do whatever you want here, knowing that up or down was not pressed.

});

Since your question is not about the debounce method you are trying to use, I've removed that from my example so you can focus on the specific issue that you are asking about.




回答3:


The problem was that the callback to the event listener needs to call the function returned from _.debounce, not just create the debounced function.

$('#search').on('keypress', function(event) {
  if (event.which === 38 || event.which === 40) {
    // do other things
    return;
  }
  _.debounce(makeRequest, 200)();
});


来源:https://stackoverflow.com/questions/43636959/conditional-debounce-depending-on-event-keycode

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