1

I'm working with ES6 for the first time, and I read some stuff about maps. From what I understand, this should be well within the possibility of ES6:

export class Elements {

    constructor() {
        this.elements = new Map();
        this.attachListeners();
    }

    textElement () {
        this.elements.set((elements.length + 1), new TextElement());
    }

    attachListeners () {
        document.getElementById('addText').addEventListener('click', this.textElement);
    }
}

However, when I click the addText element, I get the following in my console

Uncaught TypeError: Cannot read property 'set' of undefined at HTMLDivElement.textElement

I tried swapping the Map with a Set, an Array and an Object, however, that same error kept coming into my console.

How can it be that a simple operation like this isn't working?

sushibrain
  • 2,712
  • 5
  • 33
  • 62

1 Answers1

1

You need to bind your listener, like this:

document.getElementById('addText').addEventListener('click', this.textElement.bind(this));

Otherwise, this refers to your 'addText' element in your textElement function.

Try console.log(this) in textElement with and without the .bind(this) and you'll understand what's happening.

Ronan
  • 1,482
  • 11
  • 11