OpenLayers 3: Remove event listener
Asked Answered
A

2

9

In Openlayers 3 how to remove a event listener attached like this:

var a = map.on("pointerdrag",function (e) {
             // event handler
});

var b = map.on("pointerdrag",function (e) {
             // event handler
});

How do I remove only listner a and keep b active?

Accepter answered 27/8, 2015 at 15:16 Comment(0)
A
11

Ah its pretty simple! Its in the API Docs: unByKey, but very counter-intuitive name for an off function.

So to remove the event listener a:

map.unByKey(a);

Will remove a listener but keep the b on.

Note: this will work across any object in Open Layers 3 that emits an event. like Layers, Interactions etc..

Accepter answered 27/8, 2015 at 15:21 Comment(1)
Note you can also use .un, if you are using a named function. function onPointerDragOne() {/*do stuf*/} function onPointerDragTwo() {/*do stuf*/} map.on("pointerdrag", onPointerDragOne); map.on("pointerdrag", onPointerDragTwo); map.un("pointerdrag", onPointerDragOne); // Only onPointerDragTwo will runPathoneurosis
I
1

I was just wondering the same thing, seems like off would be the appropriate method to remove an event listener. You can also call this directly in the event callback:

map.on("pointerdrag", function (e) {
    map.unByKey(e);
});

This should remove only the this specific event.

Intelligible answered 29/5, 2016 at 19:21 Comment(1)
Why I'll do such thing?Erythroblastosis

© 2022 - 2024 — McMap. All rights reserved.