htmlangulartypescriptopenlayers

How to Remove EventListener in OL 9.2.4 (Angular)


SO I'm using the map.on to add my event and when I try to use the map.un it just doesn't remove the event. There is no error message or else. Here is my code:

  public selectViewMode() {
    this.map.un("singleclick", this.addMarker);
  }

This Method always gets Called first:

  public selectAddMode() {
    this.map.on("singleclick", this.addMarker.bind(this))
  }
  addMarker(event: MapBrowserEvent<UIEvent>) {
    let coordinates = event.coordinate;
    this.popup.setPosition(coordinates);

    let feature = new Feature({
      geometry: new Point(coordinates),
      name: 'Bikertreff',
    })
  
    const iconStyle = new Style({
      image: new Icon({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: 'data/marker-black.svg',
      }),
    });
    feature.setStyle(iconStyle);
  
    this.source.addFeature(feature);
  }

I also tried map.removeEventListener("singleclick") but it also didn't work


Solution

  • let func = function() {
      
    }
    
    console.log( func === func, func === func.bind(this))

    As shown in the snippet, binding the function gives another reference

    so you what you can do is

      bindedFunc = this.addMarker.bind( this );
    
      public selectViewMode() {
        this.map.un("singleclick", this.bindedFunc);
      }
    
      public selectAddMode() {
        this.map.on("singleclick", this.bindedFunc)
      }