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?

alpha787
  • 171
  • 4
  • 10
  • 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. – Felix Kling Nov 13 '21 at 00: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))` – Keith Nov 13 '21 at 00:11

1 Answers1

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')
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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. – Keith Nov 13 '21 at 00:51
  • The class is from a package so I have no way of controlling how A is defined. – alpha787 Nov 13 '21 at 00:58
  • 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. – Bergi Nov 13 '21 at 02:33