何在addEventListener处理函数内部调用Typesc

何在addEventListener处理函数内部调用Typesc

本文介绍了Angular 2-如何在addEventListener处理函数内部调用Typescript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在添加到页面跨度的处理函数中调用另一个(任何类型的)打字稿函数.当我这样做时,处理程序函数可以正常工作,并且可以完成诸如设置变量,console.log等基本操作.但是,当尝试调用任何类型的函数时,它将引发错误无法读取属性functionName of undefined'.因此,例如,下面的代码可以正常工作:

I'm trying to call another typescript function (of any kind) inside of a handler function added to spans on a page. When I do this, the handler function works fine and will do basic things such as set variables, console.log, etc. However, when trying to call a function of any kind it will throw an error of 'Cannot read property functionName of undefined'. So for example, here is code that works:

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);
}

但是,如果我更改处理程序函数以执行以下操作(或调用位于任何位置,甚至在同一组件中的任何函数),它将无法正常工作并引发错误:

However, if I change the handler function to do the following (or call any function located anywhere, even in the same component) it will not work and throws the error:

showExcerptInfo () {
  let excerpt = this.excerptsService.getExcerpt(this.selectedExcerptId);
}

关于这种情况为什么发生和/或如何解决的任何线索?

Any clues as to why this is happening and/or how it can be resolved?

推荐答案

您需要注意 this 始终指向当前的类实例:

You need to take care that this keeps pointing at the current class instance:

iterateEl[i].addEventListener('click', this.showExcerptInfo.bind(this));

或者您可以使用

iterateEl[i].addEventListener('click', (evt) => this.showExcerptInfo(evt));

这篇关于Angular 2-如何在addEventListener处理函数内部调用Typescript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:06