GEOG 863
GIS Mashups for Geospatial Professionals

Removing Event Listeners

PrintPrint

The previous page made reference to a note from Esri's Working with Events page in the API documentation. That page contains another important suggestion:

As a best practice, and to avoid memory leaks, event listeners should be removed when the application is closed. This is done by adding another listener, this time for the map's onUnload event...
var myUnload = map.on("unload", unloadHandler);

In your "unload" handler function, you disconnect the listeners, including any listener you added for the onUnload event:
function unloadHandler(evt){ changeHandler.remove(); myUnload.remove(); }

To see this concept illustrated more fully, please refer to this alternate version of the map from the last page. The differences in this version:

  1. References to the listeners set up for the two layers' load events are stored in variables.  (The listeners were simply created before without storing references to them.)
  2. The createMapAddLayers() function ends with the creation of a listener for the map's unload event, which triggers a call to a new function called removeListeners().
  3. The removeListeners() function calls on the remove() method belonging to each of the three listeners defined earlier to clean up the memory used by those listeners.

At this point, we've gone over some of the basics of setting up an Esri JavaScript API map.  And while there's often good use cases for adding graphic overlays to a map, data are more typically added by consuming services published via ArcGIS Server.  So let's explore how to go about doing that.