views:

22

answers:

1

Let's take some pseudo-Mootools code:

for loop (i) from 0 to 5 {
    create.element {
        id: 'element_'+i
    }
    $('element_'+i).addevent.click {
        alert(i);
    }
}

The events get added to the elements properly. However, when clicked, they'll all alert the latest iterator... which would be 5.

Is there any way I can change "alert(i)" in the event to alert the iterator at that point in time?

.toString didn't do much.

+1  A: 

http://www.jsfiddle.net/dimitar/sbytJ/1/

for (var ii = 0; ii < 5; ++ii) {
    new Element("div#id_" + ii + ".monkey[text=click me]").store("id", ii).addEvent("click", function() {
        alert(this.retrieve("id") + " id: " + this.get("id"));
    }).inject(document.body);

}

using the element storage (element.store("id", ii) / this.retrieve("id")) is one way of ensuring correct value reference at runtime...

another way via an anonymous function: http://www.jsfiddle.net/dimitar/sbytJ/2/

for (var ii = 0; ii < 5; ++ii) {
    (function(id) {
        new Element("div#id_" + id + ".monkey[text=click me]").addEvent("click", function() {
            alert(id);
        }).inject(document.body);
    })(ii);
}

etc etc. i am sure there are other ways to refactor this also

Dimitar Christoff