首页 > 解决方案 > 将 Javascript 重构为类对象的问题

问题描述

我尝试将我的 Javascript 代码重构为类对象 javascript 代码,但我遇到了一些问题。

我正在运行的旧代码是这样开始的:


  document.addEventListener("DOMContentLoaded", function(event) {

    // Variables :
    var color = "#000000";
    var sign = false;
    var begin_sign = false;
    var width_line = 5;
    var canvas = document.getElementById('canvas');
    var cursorX, cursorY;
    var context = canvas.getContext('2d');


    context.lineJoin = 'round'; 
    context.lineCap = 'round'; 


    document.addEventListener("mousedown", function(e) {
        sign = true; // Coordonnées de la souris :
        cursorX = (e.pageX - this.offsetLeft);
        cursorY = (e.pageY - this.offsetTop);
    });

我的新代码是这样开始的:

"use strict";
class Signature {
  constructor() {
    this.color = "#000000";
    this.sign = false;
    this.begin_sign = false;
    this.width_line = 5;
    this.canvas = document.getElementById('canvas');
    this.cursorX, this.cursorY;
    this.context = canvas.getContext('2d');
    this.context.lineJoin = 'round';
    this.context.lineCap = 'round';
  }

  init() {
    document.addEventListener("DOMContentLoaded", event => {
      this.whenMouseDown();
      this.whenMouseUp();
      this.whenMouseMove();
      this.createSignature();
      this.clearCanvas();
      this.resetCanvas();
    })
  }

  whenMouseDown() {
    document.addEventListener("mousedown", function({
      pageX,
      pageY
    }) {
      this.sign = true;
      this.cursorX = (pageX - this.offsetLeft);
      this.cursorY = (pageY - this.offsetTop);
    })
  }

但似乎不正确。如何更正我的代码?

标签: javascript

解决方案


请注意,注释代码是针对您代码中未实现的功能的。

如果您正在寻找传统方法,这是实现目标的方法。

init()移至构造函数,并且事件处理程序采用了一种非常干净的方法。

鉴于您的方法(以及其他答案的方法),每次单击鼠标时,document您都会创建一个新的事件处理程序,每次单击鼠标等都会调用该事件处理程序。

在构造函数中设置事件处理程序可以防止这种情况。

"use strict";
class Signature {
  constructor() {
    this.color = "#000000";
    this.sign = false;
    this.begin_sign = false;
    this.width_line = 5;
    this.canvas = document.getElementById('canvas');
    this.cursorX, this.cursorY;
    this.context = canvas.getContext('2d');
    this.context.lineJoin = 'round';
    this.context.lineCap = 'round';
    //    this.createSignature();
    //    this.clearCanvas();
    //    this.resetCanvas();
    this.whenMouseDown = this.whenMouseDown.bind(this);
    //this.whenMouseUp = this.whenMouseUp.bind(this);
    //this.whenMouseMove = this.whenMouseMove.bind(this);

    document.addEventListener("mousedown", this.whenMouseDown);
    //    this.document.addEventListener("mousedown", this.whenMouseUp);
    //    this.document.addEventListener("mousedown", this.whenMouseMove);
  }

  whenMouseDown(e) {
    this.sign = true;
    this.cursorX = (e.pageX - this.offsetLeft);
    this.cursorY = (e.pageY - this.offsetTop);
  }
}
<canvas id="canvas"></canvas>

推荐阅读