Javascript d3.event在去抖动函数内为null

Javascript d3.event在去抖动函数内为null,javascript,d3.js,svg,dom-events,Javascript,D3.js,Svg,Dom Events,尝试使用mousemove事件处理程序的取消公告版本时,d3.event为null。我想在此反弹跳处理程序中使用d3.mouse对象,但d3.event返回null并抛出错误。如何在以下代码中访问d3.event: // a simple debounce function function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = a

尝试使用mousemove事件处理程序的取消公告版本时,
d3.event
null
。我想在此反弹跳处理程序中使用
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如果你想看到它的作用。正在尝试将鼠标移动到
rect
元素上

之所以会发生这种情况,是因为D3在事件完成后删除事件变量,因为debounce在被调用为“延迟”且事件已消失时使用超时

要解决这个问题,您可以使用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;
    }

  };
}

回答得很好!它解决了我的问题,非常感谢