Jas*_*son 3 javascript typescript angular
我试图在页面上添加到跨越的处理函数内调用另一个打字稿函数(任何类型).当我这样做时,处理函数工作正常,并将执行基本的事情,如设置变量,console.log等.但是,当试图调用任何类型的函数时,它将抛出一个错误'无法读取属性functionName of undefined ".例如,这里是有效的代码:
addListenter() {
if (!this.addListenerFired) {
let iterateEl = this.el.nativeElement.querySelectorAll('span');
for (let i = 0; i < iterateEl.length; i++) {
iterateEl[i].addEventListener('click', this.showExcerptInfo);
}
this.addListenerFired = true;
}
showExcerptInfo (): void {
this.selectedExcerptId = event.srcElement.id;
console.log(this.selectedExcerptId);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我更改处理程序函数以执行以下操作(或调用位于任何位置的任何函数,即使在同一组件中),它将无法工作并抛出错误:
showExcerptInfo () {
let excerpt = this.excerptsService.getExcerpt(this.selectedExcerptId);
}
Run Code Online (Sandbox Code Playgroud)
关于为什么会发生这种情况和/或如何解决这个问题的任何线索?
Gün*_*uer 10
您需要注意this不断指向当前的类实例:
iterateEl[i].addEventListener('click', this.showExcerptInfo.bind(this));
Run Code Online (Sandbox Code Playgroud)
或者你可以使用
iterateEl[i].addEventListener('click', (evt) => this.showExcerptInfo(evt));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2579 次 |
| 最近记录: |