0

i would like to know how can i refer from the style function to a method or a variable which is declared outside the style function. when i try to use this inside the style function it refers always to the members inside the style function. please let me know how to be able to call a method or refer to a variable declared outside the scope of the style function

code

return new VectorTileLayer({
    source: new VectorTileSource({
        format: new MVT(),
        url: environment.LHForVectorTileSourceAsMVTTileForZXYWS + zoneToken + "/" + siteId + "/" + threshold + "/" + visualisation_operation_id + "/{z}/{x}/{y}",
    }),
    opacity: .4,
    style: function (feature){
        // console.log("MVTTileAsFeature:",feature)
        let fillColor
        let strokeColor
        let text = ""
        if (feature.get(environment.KEY_OF_MVT_FEATURE_IS_TREATMENT) == true) {
            if (feature.get(environment.KEY_1) >= 0 && feature.get(environment.KEY_1) <= 12.5){
                text = feature.get(environment.KEY_1) + "%"
                fillColor = '#ff0000'
                strokeColor = '#000000'
            } else if (feature.get(environment.KEY_1) > 12.5 && feature.get(environment.KEY_1) <= 15) {
                text = feature.get(environment.KEY_1) + "%"
                fillColor = '#fd4900'
                strokeColor = '#000000'
            }
        }
        return new Style({
            fill: new Fill({
                color: fillColor
                }),
            stroke: new Stroke({
                color: strokeColor,
                lineDash: [1],
                width:1,
                }),
                text: new Text({
                font: 'Normal 12px Arial',
                text: ''+text,
                fill: new Fill({
                    color: '#000000'
                }),
                stroke: new Stroke({
                    color: '#000000',
                    width: 0
                }),
                // offsetX: -45,
                // offsetY: 0,
                // rotation: 0
                })
            })
    }
    });
}
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

0

To refer to another method/function you have two options, either using arrow function or bind function. bind will set up your this to proper value in runtime.

Example with arrow function:

let getFillColor = () => this.myFillColor();

return new Style({
    fill: new Fill({
        color: getFillColor()
    }),
    ...
});

Example with bind:

let getFillColor = this.myFillColor.bind(this);

return new Style({
    fill: new Fill({
        color: getFillColor()
    }),
    ...
});
mimo
  • 6,221
  • 7
  • 42
  • 50