如何在addEventListener中移除事件监听器?

9

我有一个 addEventListener ,它会根据点击次数多次触发,如何确保它只运行一次?我尝试使用 removeEventListener ,但它根本没有运行。

非常感谢任何帮助和建议。提前致谢:)

Provider.ts

addInfoWindow(marker,ListingID){

this.http.get(this.baseURI + '/infoWindow.php?id=' + ListingID)
  .map(res => res.json())
  .subscribe(Idata => {

    let infoData = Idata;

      let content = "<ion-item>" + 
     "<h2 style='color:red;'>" + infoData['0'].ListingTitle + "</h2>" + 
     "<p>" + infoData['0'].ListingDatePosted + ' ' + infoData['0'].ListingStartTime + "</p>" +
     "<p> Salary: $" + infoData['0'].ListingSalary + "</p>" +
     '<p id="' + infoData['0'].ListingID + '">Apply</p>'
     "</ion-item>";    

  console.log("CREATING INFOWINDOW WITH CONTENT");
 let infoWindow = new google.maps.InfoWindow({

 content: content

 });

  google.maps.event.addListener(infoWindow, 'domready', () => { 

  let goInfoPage = document.getElementById(infoData['0'].ListingID);

    console.log("GETTING PAGE ID");

    //let it run only once, currently will increment by 1 if infoWindow if closed and reopen
  goInfoPage.addEventListener('click', () => {

    let pushData = infoData['0'];

    console.log("GETTING PAGE DATA");

    let nav = this.app.getActiveNav();

    console.log("PUSHHING TO PAGE");

    nav.push('StoreInfoPage',{'record':pushData});

  }) 

 goInfoPage.removeEventListener('click', () => {      
  console.log("REMOVE EVENT LISTENER"); // did not run
  });

 });


google.maps.event.addListener(marker, 'click', () => {
console.log("MARKER CLICKED, OPENING INFOWINDOW");
infoWindow.open(this.map, marker); 

  });


 });

}

你想要什么?在addEventListener的回调函数中调用removeEventListener,并将参考传递给你在addEventListener中使用的功能。 - Max Koretskyi
2个回答

12

removeEventListener接受作为监听器之前使用addEventListener添加的函数,而不是回调函数。因此,使用匿名函数作为监听器不实用,因为它们无法被删除。

这是通用的JavaScript知识,与Angular无关:

const onClick = () => {
  ...
  goInfoPage.removeEventListener('click', onClick);
});

goInfoPage.addEventListener('click', onClick);

Angular应用程序通常依赖于RxJS,它可以:

import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/first';

...
Observable.fromEvent(goInfoPage, 'click').first().subscribe(() => {
  ...
});

RxJS 处理监听器的移除。


10
请注意,once 选项允许避免显式删除事件监听器:goInfoPage.addEventListener('click', onClick, {once: true});。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener - Sylvain Lesage

3
您需要将函数传递给removeEventListener,如下所示:
let div = document.getElementById("myDiv");

let coolFunction = () => {
    console.log("Hello World");
    div.removeEventListener("click", coolFunction);
}

div.addEventListener("click", coolFunction);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接