0

I'm trying to add an object method to an EventListener on an HTML element. But when I do that the this variable becomes the elements itself instead of the object.

class Foo {
  constructor(element, data) {
    this.data = data;
    this.input = element;
    this.input.oninput = this.update;
  }

  update() {
    this.data; // The context has changed to the element
  }
}

Here's my workaround:

class Foo {
  constructor(element, data) {
    this.data = data;
    this.input = element;
    this.input.Foo = this;
    this.input.oninput = this.update;
  }

  update() {
    this.Foo.data;
  }
}

However, I feel like this isn't the most elegant way of formatting this. How do I program it in such a way that the object's method remembers the object it was apart of?

1 Answer 1

1

Function.prototype.bind() may help - it takes an argument and uses it as its this value.

var foo = new Foo();
var boundUpdate = foo.update.bind(foo);
boundUpdate();
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what i needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.