将对象函数传递给eventlistener javascript

时间:2016-02-12 06:58:50

标签: javascript ecmascript-6

我正在尝试将成员函数附加到canvas eventListsner。好像它无法吸收它。以下是html代码的片段。 我确实希望将我的事件与特定对象相关联,并且不希望它是静态的。

<!DOCTYPE html>
<html>
<body>
<p>Graph</p>
<canvas id="canvasGraph" width="600" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</br>
<p><button onclick="main()">Try it</button></p>

<script>
"use strict";

var cg;

function main() 
{
    var canvasElement = document.getElementById("canvasGraph");
    cg = new CanvasClass(100, canvasElement);
    //alert(cg.test);
    cg.addGraphListener();
}

class CanvasClass
{

    constructor(_testInt, _canvasElement)
    {
        this.test = _testInt;
        this.canvasElement = _canvasElement;
    }

    getMousePos(evt)
    {
        var canvas = this.canvasElement;
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
    }

    writeMessage(message) {
        var canvas = this.canvasElement;
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.font = '18pt Calibri';
        context.fillStyle = 'black';
        context.fillText(message, 10, 25);
      }

    addGraphListener()
    {
        //alert(this.test);
        this.canvasElement.addEventListener('click', this.testfunc, false);  // Not as expected
        this.canvasElement.addEventListener('click', this.listener, false);  
        this.canvasElement.addEventListener('click', CanvasClass.staticTest, false); 
    }

    static staticTest()
    {
        alert(cg.test); // works but clumsy
    }

    testfunc()
    {
        alert(this.test); // object is not recognized
    }

    listener(evt) 
    {
        //var mousePos = this.getMousePos(evt); // Uncaught TypeError: this.getMousePos is not a function
        var mousePos = getMousePos(evt);    // Uncaught ReferenceError: getMousePos is not defined 
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        this.writeMessage(message);
    }
}

</script>

1 个答案:

答案 0 :(得分:0)

试试这个

CanvasClass.protype.addGraphListener = function()
{
        var tfunc = this.listener;
        this.canvasElement.addEventListener('click', function(event){

           tfunc (evt);

        }, false);  
}

CanvasClass.protype.listener = function(evt) 
{
    var mousePos = this.getMousePos(evt); 
    var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
    this.writeMessage(message);
}

CanvasClass.protype.getMousePos= function(evt) 
{
    var canvas = this.canvasElement;
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}