T
T
thirteen_bit2021-02-03 23:19:34
JavaScript
thirteen_bit, 2021-02-03 23:19:34

How to make objects interact with each other?

I'm writing a small solution for editing the indents of html elements using the drag'n'drop method. I tried to formulate the question in the form of a problem. The page has a certain EditArea, inside it there are Edge objects, the width of which can be changed by Control objects. When interacting with the Control object, its position changes, you also need to change the width of the corresponding Edge and pass information about the change to the EditArea. I'm not strong in OOP, I added classes below and described their relationship through composition. I ask you to suggest which design pattern is best suited to my task. I hope I didn't write too confusingly, any hint on the problem will be very valuable, thanks!

class EditArea {
  #edges = [];
  constructor() {
    this.#edges.push(new Edge());
  }
  sendMessage(edge, width) {
    console.log('Изменена ширина грани: ' + width);
  }
}

class Edge {
  #width;
  #control;
  constructor() {
    this.#control = new Control();
  }
  changeWidth(value) {
    this.#width += value;
  }
}

class Control {
  #position = 0;
  /* обработчик события, срабатываемого при взаимодействии с объектом Control */
  onmove() {
    this.#position += 10;
    // здесь нужно заставить сработать changeWidth у Edge
    // и sendMessage у EditArea
  }
}

let editor = new EditArea();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2021-02-04
@SilenceOfWinter

wrap objects in a proxy or register event handlers

class Control {
  #position = 0;
  on(eventName, listener) {
     if (typeof this['on' + eventName] !== 'function') {
         throw new Error('Event "' + eventName + '" not exists');
     }
     this.addEventListener(eventName, listener);
  }
  fire(eventName) {
       let event = new CustomEvent(eventName, {detail: this});
       return this.dispatchEvent(event);
  }
  onmove() {
    this.#position += 10;
    return this.fire('move'));
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question