1
var calendar = {
  activeDates: null,

  dateClicked: function () {
    this.activeDates = document.querySelectorAll(
      '[data-calendar-status="active"]'
    )
    for (var i = 0; i < this.activeDates.length; i++) {
      this.activeDates[i].addEventListener('click', this.eventListener)
    }
  },

  eventListener: function () {
    this.removeSelectedClass()
    this.classList.add('vcal-date--selected')
  },

  removeSelectedClass: function () {
    // details omitted
  },

  dateChecked: function () {
    //will call removeEventListener here
  }
}

I want to call the function removeSelectedClass() in the event listener callback eventListener, and I know for sure this.removeSelectedClass() is wrong as this this refers to the context object this.activeDates[i] instead of calendar. A simple solution involves creating an anonymous function for the event listener callback but it is not possible in this case because I want to reuse eventListener in dateChecked. What should I do?

Jiang Ng
  • 13
  • 3
  • Can you show the code that gives your context? There is no answer unless you show how you use your object. – GetSet Feb 24 '20 at 08:14
  • @GetSet - That's shown in `eventListener` above: `this.removeSelectedClass()` (which the OP says, correctly, they know isn't right). – T.J. Crowder Feb 24 '20 at 08:15

1 Answers1

2

The methods in calendar close over the calendar variable, so you can just use calendar.removeSelectedClass():

    eventListener: function () {
      calendar.removeSelectedClass()
//    ^^^^^^^^
      this.classList.add('vcal-date--selected')
    },

In the more general case, if these are DOM event listeners, you could use the usual this solutions so that this within eventListener is calendar, accept the event parameter to eventListener, and use event.currentTarget to refer to the element when adding the class list (event.currentTarget.classList.add(...)). By default, event.currentTarget is the same as this (it's the element you hooked the event on). But you don't need to do that here since calendar is a singleton and eventListener has access to it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875