Kar*_*yak 1 javascript angular
我需要在它触发后立即删除wheel事件.我尝试了以下但不删除eventlistener.
export class HomeComponent implements OnInit {
constructor() {}
ngOnInit() {
document.querySelector("#section-one").addEventListener("wheel", () => this.myFunction1(), true);
}
myFunction1() {
alert();
document.querySelector("#section-one").removeEventListener("wheel", this.myFunction1, true);
console.log("Done!");
}
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
根据文件:
使用不标识EventTarget上任何当前注册的EventListener的参数调用removeEventListener()无效.
你的代码不应该工作.
可能的修复方法如下:
wheelHandler: any;
ngOnInit() {
this.wheelHandler = this.myFunction1.bind(this);
document.querySelector("#section-one").addEventListener("wheel", this.wheelHandler, true);
}
myFunction1() {
alert();
document.querySelector("#section-one").removeEventListener("wheel", this.wheelHandler, true);
console.log("Done!");
}
Run Code Online (Sandbox Code Playgroud)
where wheelHandler是一个引用同一个处理程序实例的函数
有关更多角度方式的解决方案
但是useCapture还不支持AFAIK 参数.所以它总是如此false
您可以使用 HostListener 装饰器来绑定事件侦听器,但这仅适用于宿主元素。如果要为子元素添加和删除侦听器,则必须使用Renderer2.listen方法。它返回一个函数来删除事件侦听器。
@Component( {
template: '<div #sectionOne></div>'
})
export class myComponent {
private _listeners = [];
@ViewChild('sectionOne')
public section: ElementRef<any>;
constructor(private _renderer: Renderer2) {}
ngAfterViewInit() {
this._listeners.push(
this._renderer.listen(this.section.nativeElement, 'click', this.handler.bind(this))
);
}
ngOnDestroy() {
this._listeners.forEach(fn => fn());
}
public handler() {
}
}
Run Code Online (Sandbox Code Playgroud)
useCaptureangular 目前不支持该参数。有关更多信息,请参阅此问题。
| 归档时间: |
|
| 查看次数: |
5822 次 |
| 最近记录: |