Skip to content Skip to sidebar Skip to footer

Echoing The "then" State Of Variable In A Mootools Event Even After Var Has Changed

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); } }

Solution 1:

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

for (var ii = 0; ii < 5; ++ii) {
    newElement("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) {
        newElement("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

Post a Comment for "Echoing The "then" State Of Variable In A Mootools Event Even After Var Has Changed"