javascript - How can I make async await work inside a class?
问题描述
I am trying to make an async await function work in a class, but while my delegated event handlers fire, somehow the variable this.shows
inside the assigned function is undefined.
this.shows.length
in previousRangeShows()
returns 0 because this.shows
is empty, but getShows()
returns the shows properly with a length of 101.
export default class Shows {
constructor() {
console.log('Created Shows')
this.RANGE = 4
this.shows = []
this.position = 0;
shows.setupDelegatedEventHandlers()
}
async getShows() {
console.log('Getting shows from JSON...')
this.shows = await $.getJSON('../json/shows.json')
this.position = this.shows.length - this.RANGE
this.renderSelectionOfShows(this.position, this.shows.length)
console.log('this.shows.length: ', this.shows.length)
}
nextRangeShows() {
console.log('>>> next shows')
if (this.position + 1 + this.RANGE < this.shows.length) {
this.position += this.RANGE
$('main').html = ''
this.renderSelectionOfShows(this.position, this.RANGE)
}
}
previousRangeShows() {
console.log('<<< previous shows')
if (this.position > 0) {
this.position -= this.RANGE
$('main').html = ''
this.renderSelectionOfShows(this.position, this.RANGE)
}
}
setupDelegatedEventHandlers() {
$('main').on('click', '#left-arrow', this.previousRangeShows)
$('main').on('click', '#right-arrow', this.nextRangeShows)
}
renderSelectionOfShows(start, range) {
$('main').append(`<img class="arrow" id="left-arrow" src="../images/left_bracket_white.png">`)
for (let i = start; i < range; i++) {
$('main').append(`<div id="shows"><p>
<strong>${this.shows[i].film}</strong><br>
Saloon: ${this.shows[i].auditorium}<br>
${this.shows[i].date} - ${this.shows[i].time}
</p></div>`)
}
$('main').append(`<img class="arrow" id="right-arrow" src="../images/right_bracket_white.png">`)
}
renderAllShows() { //unused
for (let show of this.shows) {
$('main').append(`<p>
Movie: <strong> ${show.film} </strong><br>
Saloon: ${show.auditorium}<br>
Date: ${show.date} - ${show.time}
</p>`)
}
}
}```
解决方案
推荐阅读
- reactjs - 在 React 中,如何将标签的 href 属性设置为环境变量的值?
- java - jeprof 的 java 调试符号
- linux - 将程序输出分配给shell脚本中的变量
- android - 布局方向在 ConstraintLayout 中不起作用
- python - 代码格式化,基本温度应用
- gremlin - 如何使用 Gremlin 在 valueMap 中指定要忽略的属性?
- kotlin - Kotlin 获取声明的成员属性值
- java - 我创建了带有标题和持续时间的歌曲类,以及带有 ArrayList 的专辑类,我正在尝试打印列表但在哈希值中给出输出
- reactjs - 如何修改reducer中的现有数据?
- c++ - 在内核级别安全隐藏文件