我已经成功地在我的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) {}
}
然而,执行事件时出现以下错误:
未捕获的(在Promise中)TypeError:this.fetchTickets不是一个函数,位于HTMLElement. 显然它会进入changeCurrentEvent函数,但无法找到fetchTickets函数。
changeCurrentEvent
时,this
上下文已经丢失。你可以尝试使用eventSearch.addEventListener('select', this.changeCurrentEvent.bind(this))
。 - madhu sudhan<event-search @select=${this.changeCurrentEvent}>
? - Jordan Running