D3.event is null inside the debut function

When trying to use a rejected version of the mousemove event handler, d3.event is null . I would like to use the d3.mouse object in this undo handler, but d3.event returns zero and throws an error. How can I access 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 if you want to see it in action. Attempt to hover over rect .

+6
source share
1 answer

This is because D3 deletes the event variable after the event ends, since debounce uses a timeout when it receives it to the end, and its event disappears.

To solve this problem, you can use a modified version of the 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; } }; } 
+8
source

Source: https://habr.com/ru/post/983124/


All Articles