在打字稿中为亮元素组件添加事件侦听器

时间:2020-01-22 12:15:02

标签: javascript typescript lit-element

我已经在我的Typescript代码中为Lit元素组件成功添加了一个事件监听器:

async firstUpdated() {
  await this.updateComplete;

  // Add an event listener to our event-search component so we can switch the current event
  const eventSearch = document.querySelector('event-search');
  if(typeof eventSearch !== 'undefined') {
    eventSearch.addEventListener('select', this.changeCurrentEvent);
  }
}

async changeCurrentEvent(event) {
  await this.fetchTickets(event.id);
  this.currentEvent = event;
}

async fetchTickets(eventId: number) {
  try {
    this.tickets = await fetchData(ticketEndpoint(eventId))
  } catch (error) {}
}

但是,执行事件时出现以下错误:

Uncaught (in promise) TypeError: this.fetchTickets is not a function at HTMLElement.<anonymous>

显然,它确实位于changeCurrentEvent函数中,但是找不到fetchTickets函数。

1 个答案:

答案 0 :(得分:2)

您可以使用ES6箭头函数语法来避免编写this.changeCurrentEvent.bind(this)

changeCurrentEvent = async (event) => {
  await this.fetchTickets(event.id);
  this.currentEvent = event;
}