您好,我似乎不能弄清楚为什么当直接传递到 keyup 事件时,deounce 函数能够正常工作; 但是如果我将它包装在一个匿名函数中,它就不能正常工作。
我已经解决了这个问题: http://jsfiddle.net/6hg95/1/
编辑: 添加了我试过的所有东西。
超文本标示语言
<input id='anonFunction'/>
<input id='noReturnAnonFunction'/>
<input id='exeDebouncedFunc'/>
<input id='function'/>
<div id='output'></div>
JAVASCRIPT (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
触发。我不明白为什么会这样。有人能帮我理解一下吗?
剪辑
好的,那么在 # exeDeboucedFunc (你引用的那个)中没有发生退出的原因是因为函数是在匿名函数的作用域中执行的,而另一个 keyup 事件将在另一个匿名作用域中创建一个新函数; 因此,当你键入一些东西时,多次触发退出的函数(而不是触发一次,这将是预期的行为; 参见 #function
之前) ?
你能解释一下 #anonFunction
和 #function
的区别吗。这又是一个范围问题,为什么其中一个工作,而另一个不?
剪辑 现在我明白为什么会这样了。这就是为什么我需要把它封装在一个匿名函数中:
小提琴: http://jsfiddle.net/6hg95/5/
超文本标示语言
<input id='anonFunction'/>
<div id='output'></div>
JAVASCRIPT (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/>');
}
})();