document.onmousemove обрабатывается только последним созданным объектом моего класса js - PullRequest
0 голосов
/ 22 января 2019

Я пытаюсь создать класс подвижных элементов, я получаю две this.functions функции, моя функция clique хорошо работает для каждого ребенка в классе, но моя maousemauve связана только с обработкой событий mousemove.для последнего созданного объекта.

Я думаю, что проблема возникла из объявления document.onmousemove = this.maousemauve, в которое не входит оператор this., но я не нашел, как это сделать, возможно ли это сделатьчто я хочу сделать с конструктором класса или я ищу неверный путь?

//déclaration de classe, entre parenthéses, les paramètres "inconnus"qui me permettront de définir rapidement mes futurs objets!
class Domino {

  constructor(id, side1, side2, c) {
    this.id = id;
    this.side1 = side1;
    this.side2 = side2;
    this.lien = document.getElementById(id);
    this.c = c;


    this.clique = (event) => {
      this.c += 1;


      this.lien.style.position = 'absolute';



      if (this.c === 2) {
        this.c = 0;
        console.log(this);
        return this.c;
      }

      console.log(this.c);
      return this.c;

    }


    this.maousemauve = (event) => {
      if (this.c === 1) {
        console.log(this.c);
        this.lien.style.left = event.clientX - 50 + 'px';
        this.lien.style.top = event.clientY - 30 + 'px';
      }
    }


    this.lien.onclick = this.clique;
    this.lien.onmousemove = this.maousemauve;

  }
}

var d1 = new Domino("d1", 0, 1, 0);
var d2 = new Domino("d2", 0, 1, 0);
var d3 = new Domino("d3", 0, 1, 0);


console.log(d1);
console.log(d2);
console.log(d3);
body {
  width: 1000px;
  height: 800px;
}


/*j'utilise les propriétés flex pour aligner les mots au centre dans mes dominos!*/

#d1 {
  width: 100px;
  height: 60px;
  background-color: black;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

#d2 {
  width: 100px;
  height: 60px;
  background-color: black;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

#d3 {
  width: 100px;
  height: 60px;
  background-color: black;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
<body>
  <br /><br />
  <div id="d1"> d1 </div>
  <div id="d2"> d2 </div>
  <div id="d3"> d3 </div>
</body>

1 Ответ

0 голосов
/ 23 апреля 2019

Я прочитал в ваших комментариях, что вы, по-видимому, нашли решение самостоятельно ... это не сработало.

Итак, вот несколько советов:

  • Используйте Element#addEventListener() вместо Element#onXXX свойств для установки событий.
  • Добавьте свойство (Domino#isMoving в моем примере), которое позволит вам узнать, движется ли ваш элемент в данный момент. (Может быть, Domino#c был в вашем коде, но я не был уверен.)
  • Событие click обратит значение isMoving. Затем он добавит событие mousemove, если isMoving === true, или удалит его, если нет. Событие должно быть прикреплено к document, или ваша проблема: « если я переместлю свой курсор быстро, домино не будет следовать за курсором » не будет исправлено.

Проверьте в этом упрощенном примере:

class Domino {
  constructor(id) {
    this.id = id;
    this.lien = document.getElementById(id);
    
    // Allows to know if the domino is moving or not.
    this.isMoving = false;
    
    this.lien.addEventListener('click', (e) => {
      this.listenOnClick(e);
    });
  }
  
  listenOnClick(e) {
    const handleMouseMove = (e) => {
      this.listenOnMouseMove(e);
    };
  
    this.lien.style.position = 'absolute';
    
    // If not moving, it is moving...
    // Or if it's moving, it's not moving!
    this.isMoving = !this.isMoving;
    
    // If it's moving, add an event listener on the document when the mouse is moving
    if (this.isMoving) {
      // Attachs the listener on document, because the mouse is *always* on the document. So even if the mouse is outside the domino, it will move.
      document.addEventListener('mousemove', handleMouseMove);
    } // Or if it's not, remove that event.
    else {
      document.removeEventListener('mousemove', handleMouseMove);
    }
  }
  
  listenOnMouseMove(e) {
    if (this.isMoving) {
      this.lien.style.left = e.clientX - 50 + 'px';
      this.lien.style.top = e.clientY - 30 + 'px';
    }
  }
}

let d1 = new Domino('d1');
  d2 = new Domino('d2');
body {
  width: 1000px;
  height: 800px;
}

.domino {
  width: 100px;
  height: 60px;
  background-color: black;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
<body>
  <div id="d1" class="domino">d1</div>
  <div id="d2" class="domino">d2</div>
</body>
...