0

I have created a simple drawing script using canvas: http://ulrichbangert.de/div/webentwicklung/javascript/jcanvas-drawing-pad.html I need event handlers and I attach them like this (very simplyfied):

<canvas id="mycanvas" width="400" height="300"></canvas>
<script>
    var line = {
        activate: function () {
            $("#mycanvas").off();
            $("#mycanvas").on("mousemove", function (e) {
                // do something to draw line
            })
        }
    }
    var text = {
        activate: function () {
            $("#mycanvas").off();
            $("#mycanvas").on("mousemove", function (e) {
                // do something to draw text
            })
        }
    }
    line.activate();
    // later on:
    text.activate();
</script>

The problem is that I'm using the library jCanvas that attaches eventhandlers too. By

            $("#mycanvas").off();

I remove all handlers including those attached by jCanvas, so that some features don't work. How can I remove the handlers attached by me and keep the library's handlers intact?

Sempervivum
  • 928
  • 1
  • 9
  • 21
  • Give `.off()` arguments to tell it specifically which event handlers to remove, rather than removing all handlers. – Barmar Mar 24 '17 at 00:47
  • or use namespaces – andrew Mar 24 '17 at 00:53
  • when it comes to custom event handler, always use ***namespace***. Set the namespace of your own, so that it will never break any other event handlers hooked up by other libraries (or even by your own code but of various logics). E.g: `mousemove.yourNameSpace` ... – King King Mar 24 '17 at 01:22
  • 1
    @KingKing Namespace is a fine solution, many thanks for this great hint! – Sempervivum Mar 24 '17 at 09:52
  • @Barmar I knew about this but couldn't use it as the functions are anonymous and I didn't want to change the structurecompletely – Sempervivum Mar 24 '17 at 09:52

0 Answers0