2

Possible Duplicate:
Javascript closure inside loops - simple practical example
Javascript infamous Loop problem?

I have a base function, that I want to control what ends up being like a "bumpbox". My goal is to instantiate multiple instances of this and give each of the declared variables a custom config.

The object looks like this:

Project.Modules.bumpbox = function(in_trigger, container) {

    var config = {

        'speed': 500,
        'easing' : false,//will 
        'in_callback': false,
        'out_callback' : false,
        'visible': false,
        'out_trigger' : $('#bumpbox_out_trigger'),//this is set by default only change if you know what you are doing!
    };

    this.test = function() {

        //this should be the default function. 

    };

And then, from another file, I want to instantiate an instance like new Project.Modules.Bumpbox() and overwrite the test function.

var bumpbox_controllers = {

            "map" : new Project.Modules.bumpbox($('#navigation_top li.map'), $('.bumpbox.map')),
            "contact" : new Project.Modules.bumpbox($('#navigation_top li.contact'), $('.bumpbox.contact')),
            "about" : new Project.Modules.bumpbox($('#navigation_left li.about'), $('.bumpbox.about')),
            "team" : new Project.Modules.bumpbox($('#navigation_left li.team'), $('.bumpbox.team')),
            "careers" : new Project.Modules.bumpbox($('#navigation_left li.careers'), $('.bumpbox.careers')),
            "services" : new Project.Modules.bumpbox($('#navigation_left li.services'), $('.bumpbox.services'))
        };

and then I want to loop through each of those and set a custom test() function in each like this:

    bumpbox_controllers[i]['test'] = function() {

        alert(i);
    }

But when I run this code, it will switch all of the elements to the last i value called, in this case "service", not giving each a unique element.

Community
  • 1
  • 1
JonMorehouse
  • 1,313
  • 6
  • 14
  • 34

2 Answers2

4

You seem to need a closure for your loop:

for (var controller in bumpbox_controllers) {
    bumpbox_controllers[controller] = (function(i) {
        // creating a new context for i
        return function() {
            alert(i); // access the i in scope, not the controller
        }
    })(controller);
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

To allow each test() to have its own unique i, try:

bumpbox_controllers[i]['test'] = (function (i) {
    return function () {
        alert(i);
    };
}(i));​
Brian Ustas
  • 62,713
  • 3
  • 28
  • 21