开发者

Adding listener to Jquery object in constructor

开发者 https://www.devze.com 2023-03-26 05:23 出处:网络
I have the following code: <body> <canvas id=\"canvas\" height=\"300\" width=\"300\" style=\"border:1px solid\" />

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 functio开发者_高级运维n this.ctx is undefined, any ideas why? (yes I am importing jQuery 1.6.2)


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'))   
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消