0

When a button is clicked and a function is executed which is consisting of sub-functions and event listeners. Consider this:

function init() {
  canvas = document.getElementById("canvas");
  context = canvas.getContext('2d');
  context.strokeStyle = 'purple';
  context.lineWidth = 6;
  context.lineCap = 'round';
  canvas.addEventListener('mousedown', dragStart);
  canvas.addEventListener('mousemove', drag);
  canvas.addEventListener('mouseup', dragStop);
}

Is there a way to remove this event listeners as soon as the function exited or when another function is called?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Self
  • 497
  • 1
  • 6
  • 19
  • @Rajesh not a duplicate. There is difference – Self Dec 20 '16 at 09:09
  • by difference if you mean way to call, *as soon as function exits* or *when another function is called*, these are specific use cases and should be handled accordingly. For calling on exit, pass it as callback and add `if(callback) callback()` as last line. – Rajesh Dec 20 '16 at 09:39
  • 1
    As soon as which function is exited? If you remove the event listeners when `init()` exits, then the event listeners will never be used, so why did you add them in the first place? – Barmar Dec 20 '16 at 09:41

0 Answers0