openlayersopenlayers-3openlayers-6openlayers-5angular-openlayers

How to unregister .on(drawend,....) event


as shown in the below posted code, i have an event #drawEvt and it is registered for drawend. the problem i have is about unregistering the event. as shown below in the code in method deattachAll() is how i unregister it, but it seems it does not work because the logs iinside the body of the evtListenerOnDrawEnd gets displayed several times.

one more imporatant note, is the algorithm is designed so that digitize() is being called after deattachAll(). in other words, initially digitize() is called and will never be called again for a second time unless it is preceeded by a call to deattachAll()

please let me why the listener #evtListenerOnDrawEnd is invoked several times and how to fix it

code

#evtListenerOnDrawEnd = (evt, mapBuilderInstance, rasterLayer) => {
    ...
    ...
    ...
}

getDrawGeomForSource(src, geomType) {
    return new Draw({
        source: src,
        type: geomType,
    });
}

his.#drawEvt = this.#mapBuilderInstance.getDrawGeomForSource(this.#vectorSource, 'Polygon');// to init this.`#drawEvt`

digitize() {
    this.#drawEvt.on('drawend', (evt) => this.#evtListenerOnDrawEnd(
        evt, this.#mapBuilderInstance, this.#rasterLayer
    ));
}

deattachAll() {
    this.#unregisterEvtListeners();
}

#unregisterEvtListeners() {
    this.#mapBuilderInstance.unregisterEvtListener('drawend', this.#drawEvt, this.#evtListenerOnDrawEnd);
}

unregisterEvtListener(eventName, type, callbackListener) {
    if (type) {
        type.un(eventName, callbackListener);
    }
}

Solution

  • If the callback is a named function you can use

    handler = (evt) => { /* do something */ };
    draw.on('drawend', handler);
    
    draw.un('drawend', handler);
    

    If it is an anonymous function you will need

    key = draw.on('drawend', (evt) => { /* do something */ });
    
    unByKey(key);