Q:

Reference to layergroup object in Leaflet?

I want to build my custom layers control with JQuery.
My JS is like:
$(document).ready(function() {
    var map = L.map('map', {
                    center: [39.73, -104.99],
                    zoom: 10
    });

    var littleton = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'),
        denver    = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'),
        aurora    = L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.'),
        golden    = L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.');

    var cities = L.layerGroup([littleton, denver, aurora, golden]);
    cities.addTo(map);

    // use jQuery to listen for checkbox change event
    $('div#layercontrol input[type="checkbox"]').on('change', function() {    
        var checkbox = $(this);
        var layer = checkbox.data("layer");

        // toggle the layer
        if (checkbox.prop('checked')) {
            map.addLayer(layer);
        } else {
            map.removeLayer(layer);
        }
    })
});

My html is like:
<body>
    <div id="layercontrol">
        <label><input type="checkbox" data-layer="cities">Cities</label>
    </div>
    <div id="map" style="height: 100%; width: 100%"></div>
</body>

Here the map.addLayer and map.removeLayer failed due to Error: The provided object is not a Layer.. 
How can the layergroup be referenced by the "data-layer" attribute associated with the checkbox for it?

A:

You can use window[object name] in javascript to get the layer object as they were initialized before:
HTML: 
<body>
    <div id="layercontrol">
        <label><input type="checkbox" data-city="denver">denver </label>
              <label><input type="checkbox" data-city="aurora"> aurora </label>
  <label><input type="checkbox" data-city="golden">golden</label>
    </div>
    <div id="map" style="height: 100%; width: 100%"></div>
</body>

Javascript: 
........
 // use jQuery to listen for checkbox change event
    $('div#layercontrol input[type="checkbox"]').on('change', function() {    
        var checkbox = $(this);
        // window used to get the object by name
        var layer = window[checkbox.attr("data-city")];

        // toggle the layer
        if (checkbox.prop('checked')) {
            map.addLayer(layer);
        } else {
            map.removeLayer(layer);
        }
    })

.......

