【发布时间】:2014-08-09 23:21:27
【问题描述】:
您好,我似乎无法弄清楚为什么当直接传递给 keyup 事件时,去抖动功能会按预期工作;但如果我将它包装在匿名函数中,它就不起作用了。
我解决了这个问题:http://jsfiddle.net/6hg95/1/
编辑:添加了我尝试过的所有内容。
HTML
<input id='anonFunction'/>
<input id='noReturnAnonFunction'/>
<input id='exeDebouncedFunc'/>
<input id='function'/>
<div id='output'></div>
JAVASCRIPT
$(document).ready(function(){
$('#anonFunction').on('keyup', function () {
return _.debounce(debounceIt, 500, false); //Why does this differ from #function
});
$('#noReturnAnonFunction').on('keyup', function () {
_.debounce(debounceIt, 500, false); //Not being executed
});
$('#exeDebouncedFunc').on('keyup', function () {
_.debounce(debounceIt, 500, false)(); //Executing the debounced function results in wrong behaviour
});
$('#function').on('keyup', _.debounce(debounceIt, 500, false)); //This is working.
});
function debounceIt(){
$('#output').append('debounced');
}
anonFunction 和noReturnAnonFunction 不会触发去抖动功能;但最后一个function 确实会触发。我不明白为什么会这样。谁能帮我理解一下?
编辑
好的,所以在#exeDebouncedFunc(你提到的那个)中没有发生去抖动的原因是因为该函数是在匿名函数的范围内执行的,另一个keyup事件将在另一个匿名范围内创建一个新函数;因此在您键入内容时多次触发去抖动功能(而不是触发一次,这将是预期的行为;参见#function 的行为)?
您能否解释一下#anonFunction 和#function 之间的区别。这是否又是一个界定为什么其中一个有效而另一个无效的问题?
编辑 好的,现在我明白为什么会这样了。这就是为什么我需要将它包装在一个匿名函数中:
小提琴:http://jsfiddle.net/6hg95/5/
HTML
<input id='anonFunction'/>
<div id='output'></div>
JAVASCRIPT
(function(){
var debounce = _.debounce(fireServerEvent, 500, false);
$('#anonFunction').on('keyup', function () {
//clear textfield
$('#output').append('clearNotifications<br/>');
debounce();
});
function fireServerEvent(){
$('#output').append('serverEvent<br/>');
}
})();
【问题讨论】:
标签: javascript jquery lodash