0
votes

I know this seems like a common error and I have tried to implement some jquery or Dojo code to fix the problem but nothing has helped so far--I keep getting the same error: Widget Already Registered with ID...

Here is my code:

$( "div" ).remove( "#div_temperature_legend" ); //jquery        
dojo.create("div", { id: "div_temperature_legend", innerHTML: "<p></p>" }, "legendPanel"); 
var legend = new esri.dijit.Legend({
              map: map,
              layerInfos: [{ layer: layer, title: "Temperature" }],
    }, "div_temperature_legend");
legend.startup();

the above code is in a button click function and that function is itself part of a large dojo require() function; and works the first time. The jQuery line does seem to remove because the legends don't get duplicated in the newly created div_temperature_legend layer.

Anyway, I have tried dojo's destroy() function but I still get the same error. I guess somehow, somewhere I need to register this div and then destroy it. But how? where? In the context of my code?

Ideally, code should detect the widget if it exists and doesn't create another legend.

Thanks.

2
the jquery code removes the div, but the reference of the widget (i.e esri.dijit.Legent is still available in the registry. To destroy the widget, which removes the reference in the registry you need to do something like this. legend.destroy() before creating a new esri.dijit.Legend. - frank

2 Answers

1
votes

The error resides in the wrong disposal of dojo widget. Once it created, it will be set in registry hash by its ID. You could either a) dispose the widget dojo way or b) create unique ID for the widget each time.

In case you have multiple widgets of same kind the use of ID is not a good idea. better to skip the ID and use the class attribute instead. ID will be auto-assigned but you have no interest in it as selector could use the class name you assigned.

-1
votes

Here is how I implemented my solution based on @Sasha idea of unique Div IDs:

$("#"+div_legend_global).remove();
div_legend_global = "div_" + new Date().getTime().toString();//div_legend_global defined globally
dojo.create("div", { id: div_legend_global, innerHTML: "<p></p>"    }, "legendPanel"); 
var legend = new esri.dijit.Legend({
              map: map,
              layerInfos: [{ layer: layer, title: "Temperature" }],
         }, div_legend_global);
legend.startup();

So I defined a global variable called div_legend_global and then, within the button click function, assign it unique value. That unique value then becomes the ID of the create Legend() function. After subsequent calls, jquery removes the unique div, thus preventing multiple instances of the legends in display.

Now, Dojo may be keeping in its stack the div and I think it would have been better to remove from the stack. But I am okay for now.

Thanks @Sasha.