Search code examples
javascriptecmascript-6fullcalendares6-moduleses6-class

How to pass class scope instead of newly created object scope in javascript es6


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/

Solution

  • 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)