2014-08-31 38 views
0

尝试创建一个鼠标侦听器到画布对象时遇到了一个需要很长时间才能解决的问题 - 如何将对象变量(this.X,this.Y)传递给事件侦听器,例如:传递对象变量到事件侦听器

function Test() { 

    this.canvas = .... 

    this.mouseDownHandler = .... 

    canvas.addEventLIstener('mousedown', this.mouseDownListener, false); 
} 

于是我想出了以下解决方案

回答

1

这是解决方案的工作对我来说 -

function Test() { 
    this.ctx = this.canvas.getContext("2d"); 
    var self = this; 
    this.canvas.addEventListener("mousedown", 
     function(e, param) { 
       self.mouseDownHandler(e, param); 
      }.bind(null, this), false); 
} 

Test.prototype.mouseDownHandler = function(t, e) { 
    t.ctx.fillRect(e.pageX, e.pageY, 10, 10); 
};