0

I'm quite new to javascript/typescript. I have this code and I want to call a class function inside an event handler. The problem is that this is not what I expected.

class MyClass {

  private textInput: TextView;
  private _presenter: DateOptionPresenter;

  constructor(properties: { presenter: DateOptionPresenter } & CompositeProperties) {
    super(properties);
    this._presenter = properties.presenter;
    this.createUI();
  }

  private createUI() {
    this.append(
      this.textInput = new TextView({
        left: 5, right: 5, top: 5, bottom: 5
      }).on({tap: this.showDateDialog})
    );
  }

  private showDateDialog() {
    let selectedDate = new Date();
    new DateDialog({
      date: selectedDate
    }).on('select', (date) => this._presenter.fill(date))
    .open();
  }
}

So, In the last function showDateDialog(), when I call this it's in the TextView context instead of the MyClass, and this._presenter is undefined.

How can I access _presenter in there ?

adi.neag
  • 633
  • 2
  • 12
  • 27
  • please post the code line where `showDateDialog()` is called - maybe inside your template without using `.bind()` method? – messerbill Feb 01 '18 at 15:43
  • 1
    `.on({tap: this.showDateDialog})` => `.on({tap: e => this.showDateDialog(e)})` See the linked question's answers for why. – T.J. Crowder Feb 01 '18 at 15:43

1 Answers1

0

Just passing this.showDateDialog will lose the context to which the function was bound. You need either explicitly bind the context and return that or just call it inside another function.

.on({tap: () => this.showDateDialog()})
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112