Search code examples
javascriptcreatejs

javascript loop overwriting createjs object


I have this code (I've stripped it to the basics)

for (var i = 0, len = 26; i < len; i++) {
    var chr = String.fromCharCode(65 + i);

    var letter_container = new createjs.Container();
    letter_container.chr = chr;

    letter_container.addEventListener("mouseover", function(event) { 
        console.log(letter_container.chr);
    });
}

So this obviously loops through the alphabet and creates an object for each letter in the alphabet. I want it so that when I mouseover on the container (I have taken out the actual button graphic for clarity) it outputs the character I'm hovering over.

In this case, whichever letter I hover over outputs Z.

How do I make each object unique?


Solution

  • In a couple of words, JavaScript Function Scope...

    Each time round the loop letter_container gets updated and by the time any mouseover events fire chr == Z.

    Best way round this is to wrap the contents of your loop in a function, thus.

    for (var i = 0, len = 26; i < len; i++) {
        (function(chrCode){
            var chr = String.fromCharCode(65 + i);
    
            var letter_container = new createjs.Container();
            letter_container.chr = chr;
    
            letter_container.addEventListener("mouseover", function(event) { 
                console.log(letter_container.chr);
            });
        })(i);
    }
    

    This will preserve the container so that letter_container is what you were expecting.