Search code examples
jqueryhtmlcanvasjquery-eventsmousedown

Adding listener to Jquery object in constructor


I have the following code:

<body>
    <canvas id="canvas" height="300" width="300" style="border:1px solid" />
</body> 

<script>
    function maze(canvas){
       this.ctx = canvas[0].getContext("2d");
       canvas.mousedown(down);   
    }

    function down(e){
      alert(this.ctx);   
    }    
$(document).ready(function(e){   
   var m = new maze($('#canvas'))   
}); 
</script>

However in the down function this.ctx is undefined, any ideas why? (yes I am importing jQuery 1.6.2)


Solution

  • Here canvas is pointing to a jquery object and this will point to maze instance. So try this

    function maze(canvas){
           canvas.data("ctx", canvas[0].getContext("2d"));
           canvas.mousedown(down);   
        }
    
        function down(e){
          alert($(this).data("ctx"));   
        }    
    $(document).ready(function(e){   
       var m = new maze($('#canvas'))   
    });