【问题标题】:How to removeEventListener in addEventListener? [duplicate]如何在 addEventListener 中移除EventListener? [复制]
【发布时间】:2018-01-10 02:08:26
【问题描述】:

我有一个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 中使用的函数的引用

标签: javascript typescript


【解决方案1】:

removeEventListener 接受以前添加为带有addEventListener 的侦听器的函数,而不是回调。因此,将匿名函数用作侦听器是不切实际的——它们不能被删除。

这是不是 Angular 特有的常见 JavaScript 知识:

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 处理。

【讨论】:

【解决方案2】:

您必须将函数传递给removeEventListener,如下所示:

let div = document.getElementById("myDiv");

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

div.addEventListener("click", coolFunction);

【讨论】:

    猜你喜欢
    • 2020-04-19
    • 2011-08-05
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2019-06-26
    • 2020-07-18
    相关资源
    最近更新 更多