反跳功能不适用于输入事件

时间:2019-03-04 09:26:35

标签: javascript html vanilla-typescript

我已经从David Walsh博客中获得了反跳功能实现。这是正文:

function debounce(func, wait, immediate) {
    var timeout;

    return function executedFunction() {
        var context = this;
        var args = arguments;


        var later = function() {

            timeout = null;

            if (!immediate) func.apply(context, args);
        };

        var callNow = immediate && !timeout;

        clearTimeout(timeout);

        timeout = setTimeout(later, wait);

        if (callNow) func.apply(context, args);
    };
}

现在,我在html输入元素中使用此反跳功能:

 <input type="text" id="conversation_filter_recent_messages" oninput="debounce(Conversation.recentMessagesFilter,1000)" class="form-control" placeholder="Filter Conversations">

但是当我在HTML输入元素上按下键时,什么也没有发生。应用断点显示代码永远不会返回名为executeFunction的函数。

P.S:Conversation.recentMessagesFilter是我的函数,应在1秒钟后运行,并在其他文件中定义。

3 个答案:

答案 0 :(得分:1)

tkasul是正确的,您应该使用一次去抖动功能来创建去抖动功能并将其添加到输入中。

但是,要使代码正常工作,您可以执行以下操作debounce(Conversation.recentMessagesFilter.bind(this),1000)()

如此

 <input type="text" id="conversation_filter_recent_messages" oninput="debounce(Conversation.recentMessagesFilter.bind(this),1000)()" class="form-control" placeholder="Filter Conversations">

绑定是使this代表最近消息过滤器中的输入字段,但是,您可以将其值传递给以下函数:

debounce(Conversation.recentMessagesFilter,1000)(this.value)

答案 1 :(得分:0)

您应按如下所示从debounce函数调用返回的函数:  debounce(Conversation.recentMessagesFilter,1000)()

<input type="text" id="conversation_filter_recent_messages" 
 oninput="debounce(Conversation.recentMessagesFilter,1000)()" class="form-control"   
 placeholder="Filter Conversations">

答案 2 :(得分:0)

Debouncer = { timeout: null };
Debouncer.debounce = function(func, wait, immediate) {
    let ref = this;
    return function executedFunction() {
        var context = this;
        var args = arguments;
        var later = function() {
            ref.timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !ref.timeout;
        //Clear previous call back to inside debounce function
        clearTimeout(ref.timeout);
        console.log("Debounce: "+ref.timeout);
        ref.timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
Debouncer.debounce(function() {
   console.log("Call Ajax called");
}, 300)(this);