From 3e3f9e89c43d4bdd10e438bb6f7a8e4e99d60aca Mon Sep 17 00:00:00 2001 From: Andrew Date: Sat, 30 Sep 2017 15:58:10 +0200 Subject: [PATCH] [LayerGroup] Use `eachLayer` for iterations over layers (#5809) * [LayerGroup] use eachLayer method instead of for...in * [LayerGroup] use eachLayer method in getLayers method * [LayerGroup] use eachLayer method in onAdd & onRemove methods * [LayerGroup] invoke method fix - use `eachLayer` method instead of for...in - add unit test for `invoke` method * revert invoke method change --- spec/suites/layer/LayerGroupSpec.js | 16 ++++++++++++++++ src/layer/LayerGroup.js | 18 ++++-------------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/spec/suites/layer/LayerGroupSpec.js b/spec/suites/layer/LayerGroupSpec.js index a30bbd66..3767e4b4 100644 --- a/spec/suites/layer/LayerGroupSpec.js +++ b/spec/suites/layer/LayerGroupSpec.js @@ -92,4 +92,20 @@ L.geoJson(layerGroup.toGeoJSON()); }); }); + + describe("#invoke", function () { + it('should invoke `setOpacity` method on every layer', function () { + var layers = [ + L.marker([0, 0]), + L.marker([1, 1]) + ]; + var lg = L.layerGroup(layers); + var opacity = 0.5; + + expect(layers[0].options.opacity).to.not.eql(opacity); + lg.invoke('setOpacity', opacity); + expect(layers[0].options.opacity).to.eql(opacity); + expect(layers[1].options.opacity).to.eql(opacity); + }); + }); }); diff --git a/src/layer/LayerGroup.js b/src/layer/LayerGroup.js index 19951606..33c5d83a 100644 --- a/src/layer/LayerGroup.js +++ b/src/layer/LayerGroup.js @@ -77,10 +77,7 @@ export var LayerGroup = Layer.extend({ // @method clearLayers(): this // Removes all the layers from the group. clearLayers: function () { - for (var i in this._layers) { - this.removeLayer(this._layers[i]); - } - return this; + return this.eachLayer(this.removeLayer, this); }, // @method invoke(methodName: String, …): this @@ -103,15 +100,11 @@ export var LayerGroup = Layer.extend({ }, onAdd: function (map) { - for (var i in this._layers) { - map.addLayer(this._layers[i]); - } + this.eachLayer(map.addLayer, map); }, onRemove: function (map) { - for (var i in this._layers) { - map.removeLayer(this._layers[i]); - } + this.eachLayer(map.removeLayer, map); }, // @method eachLayer(fn: Function, context?: Object): this @@ -138,10 +131,7 @@ export var LayerGroup = Layer.extend({ // Returns an array of all the layers added to the group. getLayers: function () { var layers = []; - - for (var i in this._layers) { - layers.push(this._layers[i]); - } + this.eachLayer(layers.push, layers); return layers; },