0

I made this codepen where I am setting a style to a layer on an event listener.

How can I programmatically toggle the styling on and off since my attempts to unlisten to the event for that layer have been fruitless?

Ideally once I click an outside div the map would use my styling and on clicking that div again revert to original OSM styling.

Here is the piece of code that actually enables the dark mode OSM feature. I had to declare the styling function only once in order to pass it to the on and un functions with its unique signature. I understand more about OpenLayers event listeners after Mr. Mike provided help and explanation.

darkModeOSMHandler ( flag ) {
    if (this.darkOSM === null && flag === false) {
        this.darkOSMCallback = (evt) => {
            evt.context.globalCompositeOperation = 'color';
            evt.context.fillStyle = 'rgba(0,0,0,' + 1.0 + ')';
            evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
            evt.context.globalCompositeOperation = 'overlay';
            evt.context.fillStyle = 'rgb(' + [200,200,200].toString() + ')';
            evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
            evt.context.globalCompositeOperation = 'difference';
            evt.context.fillStyle = 'rgba(255,255,255,' + 0.999 + ')';
            evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
            evt.context.globalCompositeOperation = 'source-over';
        }
        this.map.getLayers().getArray()[0].on('postrender', this.darkOSMCallback );
        this.map.updateSize()
    }

    if ( flag === false) {
        this.map.getLayers().getArray()[0].on('postrender', this.darkOSMCallback );
        this.map.updateSize()
    }

    if ( flag === true) {
        this.map.getLayers().getArray()[0].un('postrender', this.darkOSMCallback );
        this.map.updateSize()
    }

    this.darkOSM = flag
}
0

1 Answer 1

0

As mentioned in this answer the problem I had was that I was reassigning the function each time and therefore un was not matching it to the binded signature of the on listener.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.