2017-10-24 3 views
1

휠 이벤트 리스너를 발생시킨 후 즉시 제거해야합니다. 나는 다음을 시도했으나 eventlistener를 제거하지 않았다.각도 4의 EventListeners를 제거하는 방법

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

의견이 있으십니까?

답변

2

:

Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect.

코드가 작동하지 않을 수 있습니다. 다음

가능한 수정 될 수 wheelHandler

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

더 각도 방향 솔루션 핸들러

의 동일한 인스턴스를 참조하는 기능을 참조

그러나 AFAIK useCapture 매개 변수는 아직 지원되지 않습니다. 항상 그렇습니다 false

+0

그것은 작동합니다! 고맙습니다. –

+0

이것은 이벤트 리스너를 추가하고 제거하는 방법이 아니라는 것을 알고 있어야합니다. – cyrix

+0

@cyrix 알아요. 이 문제에 대해서도 알고 있어야합니다. https://github.com/angular/angular/issues/11200 – yurzui

1

클래스 메서드를 콜백 함수로 사용하면 this은 더 이상 콜백 함수의 클래스를 가리 키지 않습니다.

사용이 코드 대신 이벤트 리스너를 추가합니다 :

document.querySelector("#section-one") 
    .addEventListener("wheel",() => this.myFunction1(), true); 

this.myFunction1 그게 () => this.myFunction1()가되었다. 즉, 나는 콜백 함수의 이름을 람다 (lambda) 안에 감쌌다. 마지막으로

document.querySelector("#section-one").removeEventListener("wheel", this. myFunction1, true); 

을, 그리고 가장 중요한, 당신은 왜 그런 이벤트 리스너를 사용하고 있습니다 :

리스너를 제거하는 코드는 동일하게 유지? 이것은 명확하게 Angular 방식이 아닙니다. the docs에 따르면

+0

오류 : core.es5.js : 1020 오류 형식 오류 : '의 EventTarget'에 '때 removeEventListener'을 실행하지 못했습니다 : 필요한 2 개 인자,하지만 한 존재. 이것은 내가 받고있는 오류입니다. –

+0

제 잘못입니다. 'removeEventListener()'와 같이 적어도 2 개의 매개 변수를 사용합니다. 따라서 원래 코드를 유지할 수 있습니다. – AngularChef

+0

하지만 내 문제에 대한 해결책을 제공하지 못했습니다! 그렇게하기위한 각도의 4 가지 방법은 무엇입니까? 이 문제에 대해서만 anglejs 솔루션을 찾고 있지만 앵글 4는 아닙니다. –

1

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() { 
    } 
} 

The useCapture parameter isn't supported by angular by now. For more information, see this issue .

+0

여기서 중요한 것은 useCapture 매개 변수를 사용하는 것입니다. . 귀하의 모범에 그것을 추가하십시오. 하지만 EventManagerPlugin을 오버라이드하지 마십시오. – yurzui

+0

예 패시브 이벤트 리스너가 지금까지 각도로 지원되지 않습니다. 메모를 추가합니다. – cyrix