sara1112
sara1112

Reputation: 13

Removing event Listeners in react using highcharts

I made a 3d scatter plot using highcharts library. I also made it draggable and added mouse events to it. Now, i am not able to remove the event listeners .

On a click, the chart moves.. but on second click ... i want to stop the graph from dragging. It should stop moving .

like so
 const init = (chart) => {
    window.addEventListener("click", (eStart) => {
      isClicked = true;
      console.log("click");
      const posX = eStart.chartX,
        posY = eStart.chartY,
        alpha = chartOptions.chart.options3d.alpha,
        beta = chartOptions.chart.options3d.beta,
        sensitivity = 4; // lower is more sensitive

      const drag = (e) => {
        {
          const newBeta = beta + (posX - e.pageX) / sensitivity;
          chart.options.chart.options3d.beta = newBeta;
          // Run alpha
          const newAlpha = alpha + (e.pageY - posY) / sensitivity;
          chart.options.chart.options3d.alpha = newAlpha;
          chart.redraw(false);
        }
      };

      window.addEventListener("touchmove", (e) => drag(e));
      window.addEventListener("mousemove", (e) => drag(e));

      window.addEventListener("mouseup", (e) => unBind(e));
      window.addEventListener("touchend", (e) => unBind(e));
    });
  };
  const unBind = (e) => {
    console.log("mouse up triggered");
    e.preventDefault();
    e.stopPropagation();
    isClicked = false;
    window.removeEventListener("mousemove", () => {});
  };

Upvotes: 0

Views: 431

Answers (2)

Sebastian Hajdus
Sebastian Hajdus

Reputation: 1560

I would start with our the official Highcharts React wrapper:

https://github.com/highcharts/highcharts-react

Let's say we have this scatter 3d example as our template:

https://stackblitz.com/edit/react-rhbyat?file=index.js

And you want to block moving points the second time, right?

Upvotes: 0

Eduard
Eduard

Reputation: 535

Short: Use Highcharts.removeEvent();

If you get trouble with the problem: property is not defined on "Static" simply add to the '@types/highcharts/index.d.ts' the following code:

 /**
 * Removes an event that was added with Highcharts#addEvent
 * 
 * @see {@link https://api.highcharts.com/class-reference/Highcharts#removeEvent}
 * 
 * @param element The element to remove events on.
 * @param type The type of events to remove. If undefined, all events are removed from the element.
 * @param cb The specific callback to remove. If undefined, all events that match the element and optionally the type are removed.
 */
 removeEvent(element: HTMLElement | ElementObject | object,
     type?: string,
     cb?: (evt: Event) => void): void;

Upvotes: 0

Related Questions