d3.event在去抖动函数内部为空 [英] d3.event is null inside of debounced function

查看:771
本文介绍了d3.event在去抖动函数内部为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When attempting to use a debounced version of a mousemove event handler, d3.event is null. I'd like to use the d3.mouse object in this debounced handler, but d3.event returns null and throws an error. How can I have access to d3.event in the following code:

// 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 元素上尝试鼠标移动。

A jsfiddle if you care to see it in action. Trying mousemoving over the rect element.

推荐答案

这是因为D3在事件完成后删除事件变量,因为debounce使用超时,

This happens because D3 removes the event variable after the event has finished, since debounce uses a timeout when it gets called its to late and the event its gone.

要解决这个问题,您可以使用修改版本的debounce函数保存当前事件并在调用前替换它。

To solve this you could use a modified version of your debounce function to save the current event and replace it before your call.

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;
    }

  };
}

这篇关于d3.event在去抖动函数内部为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆