Typescript类中的Javascript范围“ this”

问题描述 投票:1回答:3

切换视频(播放/暂停)时,我试图更改视频的自定义图标。

ngAfterViewInit() {
 const vdoCont = document.querySelector('.video-player');
 const vdo = vdoCont.querySelector('video');
    vdo.addEventListener('play', () => {
     console.log(this) // Here "this" refers to typescript class
     this.updateVdoIcon(this);
    });
    vdo.addEventListener('pause', () => {
     console.log(this) // Here "this" refers to typescript class
     this.updateVdoIcon(this);
    });
}

updateVdoIcon(videoElment: any) {
    console.log(videoElment); // Expecting this to be video element instead of typescript class
  }

我试图将箭头功能更改为JavaScript功能,但是在这里我不能使用我的“ updateVdoIcon”功能。

vdo.addEventListener('play', function() {
      this.updateVdoIcon(this); // Property 'updateVdoIcon' does not exist on type 'HTMLVideoElement'
});

我知道我可以使用匿名函数(如下所示)并在那里更新图标,但是如果我想在函数中分离很多代码该怎么办

vdo.addEventListener('play', function() {
 this.paused ? console.log('Play icon') : console.log('Pause icon')
});
javascript angular typescript this
3个回答
1
投票

您可以尝试这种方式,使用ElementRef您可以访问元素,然后绑定事件。

源代码来自:https://stackoverflow.com/a/41610950/9380944答案。

import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click', this.onClick.bind(this));
}

onClick(event) {
  console.log(event);
}

1
投票

在调用事件侦听器处理程序时,不会在Component的范围内调用它。因此,this不返回组件,而是控制元素。

您需要将监听器与this绑定。

vdo.addEventListener('play', (function() {
      this.updateVdoIcon(this);
}).bind(this));

请参见文档here

或者您可以捕获this作为组件并传递给事件侦听器。

let self = this;

vdo.addEventListener('play', function() {
      self.updateVdoIcon(this);
});

0
投票

您可以在回调中传递event.currentTarget,这将是您在其中定义事件监听器的元素:

vdo.addEventListener('play', (event) => {
     this.updateVdoIcon(event.currentTarget);
});

在您的代码段中,this将是箭头函数中的[[lexical this。它从词法范围(即类实例)中捕获this上下文。

© www.soinside.com 2019 - 2024. All rights reserved.