【发布时间】:2023-03-13 15:32:01
【问题描述】:
最近的 React.JS Conf 有 Flux 面板和 Kyle Davis mentioned 基于调度循环优化的去弹跳调用。谁能提供一些关于如何实现它的例子?
【问题讨论】:
标签: javascript reactjs reactjs-flux flux
最近的 React.JS Conf 有 Flux 面板和 Kyle Davis mentioned 基于调度循环优化的去弹跳调用。谁能提供一些关于如何实现它的例子?
【问题讨论】:
标签: javascript reactjs reactjs-flux flux
我的理解是它看起来像这样:
function debounce(duration) {
var _timer = null;
var toCall = [];
function dispatch() {
_timer = null;
toCall.forEach(function(opts) {
if (opts.shouldCall) {
opts.fn.apply(undefined, opts.args);
}
opts.shouldCall = false;
});
}
return function debounce(fn) {
var myAction = {fn: fn, args: [], shouldCall: false};
toCall.push(myAction);
return function() {
myAction.shouldCall = true;
myAction.args = Array.prototype.slice.call(arguments);
clearTimeout(_timer);
_timer = setTimeout(dispatch, duration);
};
};
}
这看起来很复杂,但实际上只是尾随共享去抖动。多个函数在同一个计时器上去抖动,并且所有函数都在同一个滴答声中调用。保留最新的参数(在这种特定情况下不需要,但不会导致问题)。
我们为所有(不是每个)商店创建其中一个。持续时间大多是任意的,但足以让浏览器在我们执行商店更新逻辑和 UI 更新之间呈现一个框架,这可能会使滚动感觉更灵敏。
var storeDebounce = debouncer(20);
在我们的商店,而不是这个:
emitChange: function() {
this.emit(CHANGE_EVENT);
},
我们这样做:
emitChange: storeDebounce(function() {
this.emit(CHANGE_EVENT);
}.bind(this)),
现在,如果一个或多个 store 在同一个 tick 或短暂的连续更新中多次更新(通常发生在 Promise 或其他有保证的异步代码中),我们只会为每个受影响的 store 发出一个 change 事件。
免责声明:未经测试
【讨论】:
We create one of these for all (not each) of our stores吗?
emitChange: storeDebounce?!应该在哪里定义它以影响所有商店?您能否添加一些使用 2 个商店和共享的 emitchange 的示例(如果它按我想的方式工作)?
loadash 或 underscore debouncer 是否与您的实现不同?