0

I have a class called pop which creates pop-up dialogs on a calendar created by [fullcalendar][1]

export default class pop {
  calendar = null;

  setCalendar() {
    this.calendar = new Calendar(document.getElementById('calendar'), {
      eventSourceSuccess: setMinMaxSlotTime,
    }
  };

  setMinMaxSlotTime(eventArray) {
    this.calendar.setOption('slotMaxTime', maxTime + ':59:59');
  }
}

This doesn't work because when eventSourceSuccess is triggered, this refers to Calendar instead of pop, so this.calendar is undefined in the setMinMaxSlotTime function. Is there a way to tell the setMinMaxSlotTime to use the calendar class variable instead of the Calendar variable (which does not exist)?

NOTE: I was able to make some kind of workaround as follows, first by aliasing that to this and then passing the calendar object to the function, but I feel there's a much better way.

  setCalendar() {
    const that = this;

    this.calendar = new Calendar(document.getElementById('calendar'), {
      eventSourceSuccess(eventArray) { that.setMinMaxSlotTime(eventArray, that.calendar); },
    }
  }

  setMinMaxSlotTime(eventArray, calendar) {
    calendar.setOption('slotMaxTime', maxTime + ':59:59');
  }


  [1]: https://fullcalendar.io/
mankowitz
  • 1,864
  • 1
  • 14
  • 32

2 Answers2

1

You can define the method as a class field so that the this context is automatically bound and cannot be changed.

setMinMaxSlotTime = (eventArray) => {
    this.calendar.setOption('slotMaxTime', maxTime + ':59:59');
}

Alternatively, you could bind the this value manually, like so:

this.setMinMaxSlotTime.bind(this)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

simple solution:

export default class pop {
  calendar = null;
  scope=this;
  setCalendar() {
    scope.calendar = new Calendar(document.getElementById('calendar'), {
      eventSourceSuccess: setMinMaxSlotTime,
    })
  };

  setMinMaxSlotTime(eventArray) {
    scope.calendar.setOption('slotMaxTime', maxTime + ':59:59');
  }
}

Better solution: use bind() or call()

Deepkamal
  • 330
  • 1
  • 10
  • this doesn't quite work as written because `scope.calendar` doesn't exist in `setCalendar` or in `setMinMaxSlotTime`. Maybe `this.scope.calendar` – mankowitz May 16 '23 at 22:41