无法让_.debounce()工作

问题描述 投票:0回答:1

我无法尝试使用underscore.debounce()来工作。我在输入字段上附加了一个keydown事件监听器。我将执行一些操作,然后调用未被调用的debounce()。我想知道它为什么不起作用?

我提供了两个样本。我没有将_.debounce()作为内联附加的第一个不起作用。我把_.debounce()作为内联附加的第二个是工作。我不明白为什么非内联解决方案有效?

// This example does not ever call _.debounce()
$('input').on('keydown', onKeyDown);
function onKeyDown() {
    console.log('performing some actions...');

    _.debounce(function() {
        console.log('debouncing'); // never called
    }, 500);
}


// This example does call _.debounce()
$('input').on('keydown', _.debounce(function() {
    console.log('debounce');
}, 500));
javascript underscore.js
1个回答
4
投票

Debounce返回一个需要调用的函数,在这种情况下,您正在创建一个函数,但从不调用它。试试这个:

// This example does not ever call _.debounce()
var debounced = _.debounce(debounceStuff, 500);
$('input').on('keydown', onKeyDown);
function onKeyDown() {
    console.log('performing some actions...');

    debounced();
}

function debounceStuff() {
    console.log('debouncing');
}
© www.soinside.com 2019 - 2024. All rights reserved.