Re: Evaluating variable in loop at time of creation

Thursday, May 15, 2014

Thanks very much Binary Tutor - I had found some links to this online but hadn't managed to get it to work. Now it works perfectly. Thank you.

On Thursday, May 8, 2014 10:27:45 PM UTC-7, Binary Tutor wrote:
What you need to do is create a closure.

for(i=0;i<locations.length;i++) {
    //var thisLocation;
    //thisLocation = eval('location' + (i+1));
    coords = locations[i];
    mapLocations[i] = L.mapbox.featureLayer({
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: coords
        },
        properties: {
            'marker-size': 'large',
            'marker-color': '#ec0112'
        }
    }).addTo(map);
    mapLocations[i].on('click', function(i) {
         // This is a closure. i becomes a local variable
         // to the function below.
         return function () {
            $('.rental-location').css('display', 'none');
            $('.rental-location-' + (i+1)).css('display', 'block');
         };
    }(i);
}

On Wednesday, May 7, 2014 9:05:16 PM UTC-4, Anthony Glazebrook wrote:
I am creating markers on a Mapbox page and when the marker is clicked, it needs to open a different layer on the calling page.

I tried creating a loop where the marker click event was assigned automatically based on the index of the loop, but this evaluated the index value at the time of running, rather than the time of creation.

How can I extract this index value and have it called at the time of running?

Here is the code:

// Create a map in the div #map
var map = L.mapbox.map('map', 'marashi760.heap66lg')
    .setView([lat, lng], zoom);
var locations = [
    [-122.386839, 37.650615],
    [-118.398227, 33.94466],
    [-117.191262, 32.744102],
    [-117.860223, 33.680488],
    [-118.144392, 33.818421],
    [-122.219743, 37.712569],
    [-121.925906, 37.366695],
    [-121.590065, 38.695085],
    [-117.346057, 33.163207]
];
var mapLocations = new Array();
for(i=0;i<locations.length;i++) {
    //var thisLocation;
    //thisLocation = eval('location' + (i+1));
    coords = locations[i];
    mapLocations[i] = L.mapbox.featureLayer({
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: coords
        },
        properties: {
            'marker-size': 'large',
            'marker-color': '#ec0112'
        }
    }).addTo(map);
}
mapLocations[0].on('click', function() {
    $('.rental-location').css('display', 'none');
    $('.rental-location-1').css('display', 'block');
});
mapLocations[1].on('click', function() {
    $('.rental-location').css('display', 'none');
    $('.rental-location-2').css('display', 'block');
});
mapLocations[2].on('click', function() {
    $('.rental-location').css('display', 'none');
    $('.rental-location-3').css('display', 'block');
});
// etc for all markers

I tried adding this into the loop:
    mapLocations[i].on('click', function() {
        $('.rental-location').css('display', 'none');
        $('.rental-location-' + (i+1)).css('display', 'block');
    }

but it the penultimate line always evaluates (i+1) to the value of i at the time of running, rather than creation. It seems silly that I have to manually assign the click functionality rather than iterate through the markers.

--
You received this message because you are subscribed to the Google Groups "JavaScript Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to javascript-information+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright © 2010 Web Design | Free Blogger Templates by Splashy Templates | Layout by Atomic Website Templates

Vida de bombeiro Recipes Informatica Humor Jokes Mensagens Curiosity Saude Video Games Animals Diario das Mensagens Eletronica Rei Jesus News Noticias da TV Artesanato Esportes Noticias Atuais Games Pets Career Religion Recreation Business Education Autos Academics Style Television Programming Motosport Humor News The Games Home Downs World News Internet Design Entertaimment Celebrities 1001 Games Doctor Pets Net Downs World Enter Jesus Mensagensr Android Rub Letras Dialogue cosmetics Genexus lasofia thebushrajr wingshock tripedes gorduravegetal dainfamia dejavu-transpersonal jsbenfica republicadasbadanas ruiherbon iranianforaryans eaystcheyl fotosdanadir Só Humor Curiosity Gifs Medical Female American Health Madeira Designer PPS Divertidas Estate Travel Estate Writing Computer Matilde Ocultos Matilde futebolcomnoticias girassol lettheworldturn topdigitalnet Bem amado enjohnny produceideas foodasticos cronicasdoimaginario downloadsdegraca compactandoletras newcuriosidades blogdoarmario arrozinhoii