gpt4 book ai didi

javascript - d3.event 在 debounced 函数中为 null

转载 作者:数据小太阳 更新时间:2023-10-29 05:12:17 33 4
gpt4 key购买 nike

尝试使用 mousemove 事件处理程序的去抖动版本时,d3.eventnull。我想在此去抖动处理程序中使用 d3.mouse 对象,但 d3.event 返回 null 并引发错误。如何在以下代码中访问 d3.event:

// a simple debounce function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, 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);
}
};
}

// the function to handle the mouse move
function handleMousemove ( context ) {
var mouse = d3.mouse( context );
console.log( mouse );
}

// create a debounced version
var debouncedHandleMousemove = debounce(handleMousemove, 250);

// set up the svg elements and call the debounced version on the mousemove event
d3.select('body')
.append('svg')
.append('g')
.append('rect')
.attr('width', 200)
.attr('height', 200)
.on('mousemove', function () {
debouncedHandleMousemove( this );
});

A jsfiddle如果你想看到它的实际效果。尝试将鼠标移动到 rect 元素上。

最佳答案

发生这种情况是因为 D3 在事件结束后删除了事件变量,因为 debounce 在被调用到很晚并且事件消失时使用超时。

要解决此问题,您可以使用去抖功能的修改版本来保存当前事件并在调用之前替换它。

function debounceD3Event(func, wait, immediate) {
var timeout;
return function() {
var context = this;
var args = arguments;
var evt = d3.event;

var later = function() {
timeout = null;
if (!immediate) {
var tmpEvent = d3.event;
d3.event = evt;
func.apply(context, args);
d3.event = tmpEvent;
}
};

var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
var tmpEvent = d3.event;
d3.event = evt;
func.apply(context, args);
d3.event = tmpEvent;
}

};
}

关于javascript - d3.event 在 debounced 函数中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28773113/

33 4 0
文章推荐: javascript - 为什么要将 Something 分配给 Something.prototype.constructor?
文章推荐: javascript - 检查 HTML 文件是否在线或本地文件夹
文章推荐: javascript - 如何使用 Cheerio js 删除
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com