skip to Main Content

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/

2

Answers


  1. 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()

    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search