Does anyone have an example of how to detect when a layer changes visibility? I'm trying to use the reactiveUtils but no luck.
below is what I think should work and is in one of the reactiveUtils Samples but doesn't seem to work even in the sample. (it never triggers the callback function when i turn on and off layers).
// Use reactiveUtils to check when a Collection has changed
reactiveUtils.watch(
() => [view.map.allLayers.forEach((layer) => layer.visible)],
() => {
console.log("layer visibiblity changed")
let layerNames = "";
renderVisibleLayers(layerNames);
}
);
Or perhaps there is a better way to set up an event listener on all my layers for visibility?
Thanks in advance.
Jason.
Solved! Go to Solution.
Hi there,
So I did confirm that watching layer visibility is not working in the sample you mentioned. We will get it fixed in the sample ASAP. Thank you for bringing this to our attention.
You can watch the operational layer visibilities the following way:
view.when(()=>{
view.map.layers.forEach((layer) => {
reactiveUtils.watch(() => layer.visible, (visible) => {
console.log(layer.title, "visible:", layer.visible)
});
});
});
Or for single layer you can just do the following:
reactiveUtils.watch(() => layer.visible, (visible) => {
console.log(layer.title, "visible:", layer.visible)
});
@jasonwriterhave you checked out this sample https://developers.arcgis.com/javascript/latest/sample-code/watch-for-changes-reactiveutils/ ?
Hi Andy,
Thanks, that's the one I was trying to follow but the layer visibility code isn't working in the sample.
Hi there,
So I did confirm that watching layer visibility is not working in the sample you mentioned. We will get it fixed in the sample ASAP. Thank you for bringing this to our attention.
You can watch the operational layer visibilities the following way:
view.when(()=>{
view.map.layers.forEach((layer) => {
reactiveUtils.watch(() => layer.visible, (visible) => {
console.log(layer.title, "visible:", layer.visible)
});
});
});
Or for single layer you can just do the following:
reactiveUtils.watch(() => layer.visible, (visible) => {
console.log(layer.title, "visible:", layer.visible)
});
Thank you Undral! Take care.
Hey there,
This works too: [view.map.allLayers.map((layer) => layer.visible)]
Hi @jasonwriter !
Thanks for catching this. Using Collection.forEach() worked in version 4.23 and in 4.24 we made a change to avoid calling the callback when the return value is the same. With forEach() the return value is always the same so using Collection.map() fixes this issue.
The sample will be updated to use map() mid week next week. Thanks again!