我已经在我的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
函数。
答案 0 :(得分:2)
您可以使用ES6箭头函数语法来避免编写this.changeCurrentEvent.bind(this)
。
changeCurrentEvent = async (event) => {
await this.fetchTickets(event.id);
this.currentEvent = event;
}