在 class 方法中使用事件侦听器调用另一个返回未定义的 class 方法

Using an event listener inside a class method to call another class method returning undefined

我正在学习如何使用 javascript classes。我在理解如何让事件侦听器在 class 中调用方法时遇到了一些困难。具体来说,每当我在单击时调用 this.infoBoxActive 时,方法 return 中的所有变量都未定义。

我最终想做的是有一个toggle 方法,onclick 在true 和false 之间切换,然后根据它的状态调用infoBoxActive 或infoBoxDective。我一天中的大部分时间都在玩我的代码,尝试各种事情,但我似乎引发了同样的问题,即我的变量未定义。如果我直接调用该方法,我的一切都会很好。

我一直在使用承诺从本地 JSON 文件收集我的数据,但我不确定如何 return 我决心中的对象所以现在我是从承诺中调用我所有的新 classes。我不知道这是否是问题的一部分。

我已经尝试阅读一些相似的帖子,但要么我无法理解解决方案,要么它与我的确切问题无关,所以如果这是重复的,我深表歉意。

class EpisodeInfoBox extends Episode {
  constructor({ title, date, description, tracklist } = {}) {
    super({ title, date, description, tracklist })

    this.titleContainer = document.querySelector('.episode-title');
    this.dateContainer = document.querySelector('.episode-date');
    this.descriptionContainer = document.querySelector('.episode-description');
    this.tracklistContainer = document.querySelector('.episode-tracklist');

    this.infoBoxButton = document.getElementById('infoBoxButton');

    this.infoBoxButton.addEventListener('click', this.infoBoxActive);
  }



  infoBoxActive(){
    this.titleContainer.innerHTML = this.title;
    this.dateContainer.innerHTMLs = this.date;
    this.descriptionContainer.innerHTML = this.description;

    // Creates list-items for track list
    let tracklistHTML = '';
    for (let i = 0; i < this.tracklist.length; i++) {
      tracklistHTML += `<li>${this.tracklist[i].song} - ${this.tracklist[i].artist}</li>`;
    }
    this.tracklistContainer.innerHTML = tracklistHTML;
  }
}

我的承诺

export default function service(url) {
  return new Promise(function(res, rej) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onreadystatechange = handleResponse;
    xhr.onerror = function(error) {
      rej(error)
    }
    xhr.send();

    function handleResponse() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var resObject = JSON.parse(xhr.responseText);
          res(resObject)
        } else {
          rej(this.statusText)
        }
      }
    };
  });
}

我的决心

function callService(){
  service('/data/episodes.json')
    .then(retrieveEpisode)
    .then(makeEpisode)
    .catch(function(e) {
      console.log(e)
    });
}

function retrieveEpisode(episodeArray) {
  return episodeArray[0];

}

function makeEpisode(episode){
  let newEpisode = new Episode(episode);
    newEpisode.setEpisodeImage();
  let newAudioPlayer = new AudioPlayer(episode);
  let newEpisodeInfoBox = new EpisodeInfoBox(episode);
}

改变这个:

 this.infoBoxButton.addEventListener('click', this.infoBoxActive);

对此:

this.infoBoxButton.addEventListener('click', this.infoBoxActive.bind(this));

调用事件侦听器时,它不会设置对象的 this 指针,因此使用不适当的 this 值调用 infoBoxActive(),因此您看不到您期望的属性。您可以使用 .bind() 如上所示在调用您的方法之前重新附加适当的 this 值。


在Javascript中,当你将this.infoBoxActive作为参数传递给函数时,传递了对.infoBoxActive方法的引用,但与[=根本没有任何联系12=]。它只是对函数的引用。因此,侦听器然后调用该函数并为 this 设置自己的值,这将不是您的对象。使用 .bind() 您可以创建一个函数存根,它将在调用您的函数时为您设置 this 的值。