在_.debounce()中检查参数值的优雅方法是什么?
var renderPage = _.debounce(function(pageNo){
// render code for page=pageNo immediately, then
// debounce repeated calls for the SAME pageNo
// but a DIFFERENT pageNo would have a different debounce setTimeout()
}, 1000, true)
renderPage(1); // render immediate
renderPage(1); // debounced
renderPage(2); // render immediate
renderPage(2); // debounced
答案 0 :(得分:1)
这里的答案很好,但另一种可能性就是记忆。类似的东西:
var renderPage = function (pageNo) {
renderPage._pageNos = renderPage._pageNos || {};
if (!(pageNo in renderPage._pageNos)) {
renderPage._pageNos[pageNo] = _.debounce(function () {
// Do renderPage() work here
}, 1000, true);
}
renderPage._pageNos[pageNo]();
}
答案 1 :(得分:0)
也许是这样的?
var debouncer = function(func, timer){
return _.debounce(func, timer, true);
}
var renderPage = function(num){
}
var renderPage1 = debouncer(renderPage, 1000);
var renderPage2 = debouncer(renderPage, 2000);
好的怎么样:
var rp = function(num){
//actual render page code here
}
var renderPage = function(num, timer){
if(typeof(this[num]) === "undefined"){
this[num] = _.debounce(rp, timer, true);
}
this[num](num);
}
答案 2 :(得分:0)
这是一个可能的解决方案吗?我回到了下划线源码。我认为您需要跟踪不同的setTimeout调用以完成任务。是否有一种更通用的方法可以让计时器在某个地方“静止”?
_.debounceByArgs = function(func, wait, immediate, timers) {
var timeout = timers || {};
return function() {
var context = this, args = arguments;
var id = JSON.stringify(args);
var later = function() {
timeout[id] = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout[id]);
timeout[id] = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};