Home > Mobile >  how can i set this removeEventListener's param?
how can i set this removeEventListener's param?

Time:01-12

I was about to make some rotation programm (worked by mouse click & drag) but the 'removeEventListener' doesn't work. can u explain me how to work it and why doesn't it work?

And this is my first question in here so if u find any problems about this question, I'll gladly accept it.

<body>

    <div >

        <div >target</div>

    </div>
</body>
const html = document.querySelector("html");
const info = document.querySelector(".info");

const target = document.querySelector(".target");
const wrap = document.querySelector(".wrap");
let center = {
  x: target.getBoundingClientRect().left   target.clientWidth / 2,
  y: target.getBoundingClientRect().top   target.clientHeight / 2,
};

window.addEventListener("resize", () => {
  center = {
    x: target.getBoundingClientRect().left   target.clientWidth / 2,
    y: target.getBoundingClientRect().top   target.clientHeight / 2,
  };
});

const rotate = function () {
  target.addEventListener("mousemove", (e) => {
    const x = center.x - e.clientX;
    const y = center.y - e.clientY;

    const radian = Math.atan2(y, x);
    const degree = ((radian * 180) / Math.PI).toFixed(0);
    target.style.transform = "rotate("   degree   "deg)";
  });
};

target.addEventListener("mousedown", rotate, true);

target.addEventListener("mouseup", () => {
  target.removeEventListener("mousedown", rotate, false);

});

I've tried to change this part. target -> wrap and removeEventListener's param to another one. But none of those worked

target.addEventListener("mouseup", () => {
  target.removeEventListener("mousedown", rotate, false);
});

CodePudding user response:

The capture/ use capture falg must match to remove listener. Since you used true for your mousedown even listener you also must use true to remove event listener:

target.addEventListener("mouseup", () => {
    target.removeEventListener("mousedown", rotate, true);
});

See docs for more details: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal

  • Related