Leaflet - overwriting layer on click event

584 Views Asked by At

I have a mobx reaction, that conditionaly maps layer.on({click}) function to a layer group.

reaction(
      () => this.managingDates,
      () => {
        if (this.managingDates) {
          this.mapStore.polygonLayer.eachLayer(layer => {
            layer.on({
              click: e => {
                this.mapStore.setManagedParcel({
                  feature: e.target.feature,
                  bounds: layer.getBounds()
                });
                layer.setStyle({
                  color: "red"
                });
              }
            });
          });
        } else {
          this.mapStore.polygonLayer.eachLayer(layer => {
            layer.on({
              click: e => {
                this.mapStore.setActiveParcel(e.target.feature);
                layer.setStyle({
                  color: "yellow"
                });
              }
            });
          });
        }
      }
    );

This is fine the first time around, but when the reaction triggers again with different parameters, instead of overriding the on click event, the second function gets added (so both function get called on click).

How do I remove the previous layer.on click events before adding a new one?

1

There are 1 best solutions below

0
On

Instead of adding/removing click listeners when managingDates changes, couldn't you just use a ternary in one single listener per layer?

@observer
class App extends Component {
  @observable managingDates = false;
  layerListeners = [];

  componentDidMount () {
    this.mapStore.polygonLayer.eachLayer(layer => {
      const onClick = (e) => {
        this.mapStore.setActiveParcel(e.target.feature);
        layer.setStyle({
          color: this.managingDates ? "red" : "yellow"
        });
      }
      this.layerListeners.push(onClick);
      layer.on('click', onClick);
    });
  }

  componentWillUnmount () {
    this.layerListeners.foreach(f => {
      layer.off('click', f);
    });
  }

  render () {
    // ...
  }
}