0

I'm trying to use a class from a library but want to override one of its methods. This is how the class is defined:

class A {
  constructor (options) {
    this._searchForm = options.searchForm 
    this._searchForm.addEventListener('submit', this.submitHandler.bind(this))
  }

  submitHandler = (e) => {
    console.log('Default')
  }
}

I want to override the submitHandler function and so this is what i did:

class B extends A {
  submitHandler = (e) => {
    console.log('New')
  }
}

However, it's still calling the old function. What am i doing wrong?

2
  • 1
    A's constructor is called before B's constructor, so B didn't have a chance to override submitHandler before it was bound. You could try to remove the event handler on this._searchForm and add your own. FWIW, this.submitHandler.bind(this) is unnecessary because submitHandler is an arrow function. Commented Nov 13, 2021 at 0:11
  • Your binding submit handler on A, you don't re-bind on B. But if you don't want to re-bind, you might be able to do this instead. -> addEventListener('submit', e -> this.submitHandler(e)) Commented Nov 13, 2021 at 0:11

1 Answer 1

2

A class constructor must not call (or, in this case, bind) on overridable method (see also here). It probably shouldn't even install event listeners - that's not the job of a constructor. But if you still want to do it, don't use class fields but method declarations:

class A {
  constructor (options) {
    this._searchForm = options.searchForm 
    this._searchForm.addEventListener('submit', this.submitHandler.bind(this))
  }

  submitHandler(e) {
    console.log('Default')
  }
}
class B extends A {
  submitHandler(e) {
    console.log('New')
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It never even occurred to me the OP was doing class fields, for some reason just though method = (e) => { was some fancy way of defining a method. Of course now you've pointed it out, it's obvious it's a class field.
The class is from a package so I have no way of controlling how A is defined.
Then it's either a) the class is not designed to be subclassible, use a different way to customise it or b) it's a bug in that package. Raise an issue in the library repository.

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.