You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OL 9.2.4(Angular)中移除EventListener失效问题求助

问题原因与解决方案

核心问题

你调用map.on时用了addMarker.bind(this),每次调用bind都会返回一个全新的函数实例。后续用map.un("singleclick", this.addMarker)移除时,传入的原函数和之前绑定的不是同一个引用,事件系统找不到对应的监听,所以移除无效。

另外,OpenLayers的事件系统是自定义实现的,和DOM原生事件不互通,所以map.removeEventListener也无法生效,必须用OpenLayers提供的map.un()方法。

解决方法

方法1:提前绑定函数到实例(推荐)

在类的构造函数里完成this绑定,确保addMarker的引用唯一:

constructor() {
  // 提前绑定,后续on/un都用这个固定的引用
  this.addMarker = this.addMarker.bind(this);
}

public selectAddMode() {
  this.map.on("singleclick", this.addMarker);
}

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

方法2:用箭头函数定义addMarker

箭头函数会自动绑定当前上下文的this,且函数引用固定:

// 改用箭头函数定义,无需手动bind
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);
}

public selectAddMode() {
  this.map.on("singleclick", this.addMarker);
}

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

方法3:保存绑定后的函数引用

在类中新增属性存储绑定后的函数,确保on和un用同一个引用:

// 定义属性存储绑定后的函数
private boundAddMarker: (event: MapBrowserEvent<UIEvent>) => void;

constructor() {
  this.boundAddMarker = this.addMarker.bind(this);
}

public selectAddMode() {
  this.map.on("singleclick", this.boundAddMarker);
}

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

内容的提问来源于stack exchange,提问作者kraet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:36:05