Using dojo.disconnect

1687
3
08-15-2016 08:41 AM
OliviaGill1
New Contributor

How can I use dojo.disconnect to remove a map layer I've added. My code doesn't seem to work, it adds the map layer fine but I can't remove it? Any help would be good:

<script>

var node = dojo.byId("switch1");
var eventHandle = dojo.connect(node, "onclick", function addMapLayer1(e) {
var soils1 = new ArcGISDynamicMapServiceLayer("https://map/arcgisserver/mapserver", {
opacity: 1,
"visible": true
});

dojo.disconnect(eventHandle);
soils1.setVisibleLayers([1]);
map.addLayer(soils1);

</script>

<html>

<div class="switch tiny" style=" float:right;padding-top:0px;">

<input class="switch-input" id="switch1" type="checkbox" name="exampleSwitch">
<label class="switch-paddle" for="switch1">
<span class="switch-active" aria-hidden="true">On</span>
<span class="switch-inactive" aria-hidden="true">Off</span>
</label>


</div>

</html>

0 Kudos
3 Replies
KenBuja
MVP Esteemed Contributor

You should use dojo/on for your event handling. From the Events section in the documentation:

Using the on method is preferable to using connect for several reasons. First, the Dojo documentation states that connect support will be removed in Dojo 2.0, and in fact, connect is now a legacy convenience wrapper for dojo.on. Secondly, especially in AMD style, it makes your code less verbose and is more similar to event attachment syntax in other JavaScript frameworks. Finally, for esri components we add a target property to all "synthetic" events (not mouse or key events) which points to the component which fired the event.

"dojo/on" contains the function "once", which can be set so the event only happens once and is removed afterward.

Reading your question again, are you expecting disconnect to remove the layer? If so, you'll have to do that with the removeLayer method. Disconnect just removes the event handler (meaning if you click on the button again, it won't fire the function to add the map layer.

OliviaGill1
New Contributor

Hi Ken - thank you for the response, it's helped alot. I think my problem is the fact I'm using the same 'switch' to add the map as I am to remove it. Other than adding a different switch for each event I'm guessing I should add an if clause ie. if the map layer is 'on' and the switch is clicked again then removeLayer...

Olivia

0 Kudos
FC_Basson
MVP Regular Contributor

I would use a boolean variable to "manage" the visibility of the layer and just toggle the boolean value each time the button is clicked.  Then based on the boolean value set the visibility of the layer within the onclick function.

var layerIsOn = false;
var eventHandle = dojo.connect(node, "onclick", function addMapLayer1(e) {
   layerIsOn = !layerIsOn;
   if (layerIsOn) {
      // switch layer on
   } else {
      // switch layer off
   }
});‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos