Merge pull request #1169 from tomhughes/layers

Update the Layers control when layers are added or removed
This commit is contained in:
Vladimir Agafonkin 2012-11-23 17:18:42 -08:00
commit e2daa349b1
2 changed files with 56 additions and 0 deletions

View File

@ -29,4 +29,37 @@ describe("Control.Layers", function () {
expect(spy).not.toHaveBeenCalled();
});
});
describe("updates", function () {
beforeEach(function () {
map.setView([0, 0], 14);
});
it("when an included layer is addded or removed", function () {
var baseLayer = L.tileLayer(),
overlay = L.marker([0, 0]),
layers = L.control.layers({"Base": baseLayer}, {"Overlay": overlay}).addTo(map);
spyOn(layers, '_update').andCallThrough();
map.addLayer(overlay);
map.removeLayer(overlay);
expect(layers._update).toHaveBeenCalled();
expect(layers._update.callCount).toEqual(2);
});
it("not when a non-included layer is added or removed", function () {
var baseLayer = L.tileLayer(),
overlay = L.marker([0, 0]),
layers = L.control.layers({"Base": baseLayer}).addTo(map);
spyOn(layers, '_update').andCallThrough();
map.addLayer(overlay);
map.removeLayer(overlay);
expect(layers._update).not.toHaveBeenCalled();
});
});
});

View File

@ -10,6 +10,7 @@ L.Control.Layers = L.Control.extend({
this._layers = {};
this._lastZIndex = 0;
this._handlingClick = false;
for (var i in baseLayers) {
if (baseLayers.hasOwnProperty(i)) {
@ -28,9 +29,19 @@ L.Control.Layers = L.Control.extend({
this._initLayout();
this._update();
map
.on('layeradd', this._onLayerChange, this)
.on('layerremove', this._onLayerChange, this);
return this._container;
},
onRemove: function (map) {
map
.off('layeradd', this._onLayerChange)
.off('layerremove', this._onLayerChange);
},
addBaseLayer: function (layer, name) {
this._addLayer(layer, name);
this._update();
@ -133,6 +144,14 @@ L.Control.Layers = L.Control.extend({
this._separator.style.display = (overlaysPresent && baseLayersPresent ? '' : 'none');
},
_onLayerChange: function (e) {
var id = L.stamp(e.layer);
if (this._layers[id] && !this._handlingClick) {
this._update();
}
},
// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
_createRadioElement: function (name, checked) {
@ -184,6 +203,8 @@ L.Control.Layers = L.Control.extend({
inputsLen = inputs.length,
baseLayer;
this._handlingClick = true;
for (i = 0; i < inputsLen; i++) {
input = inputs[i];
obj = this._layers[input.layerId];
@ -201,6 +222,8 @@ L.Control.Layers = L.Control.extend({
if (baseLayer) {
this._map.fire('baselayerchange', {layer: baseLayer});
}
this._handlingClick = false;
},
_expand: function () {