javascriptscopedom-eventstitaniumtitanium-mobile

Titanium : Attach objects/variables with a view


I am creating some views in a loop iterating over list of objects. Now I want to register event with each view, which does something on the current object of the list.

for (var vs = 1; vs < 4; vs++) {
    iMovie = moviesList[vs];
    if (!iMovie) {
        break;
    }

    var loopView = Ti.UI.createView({
        ....
    });

    loopView.addEventListener("click", function(e) {
        var mv = iMovie;
        Ti.API.info("Movie: " + mv);
        if (mv) {
            // do something
        }
    });
}

This code is not working, the log which is printed is : Movie: undefined.

So my question is how I can use the loop variable in the event listener?


Solution

  • Try the following code

    var loopView - [];
    var iMovie;
    for (var vs = 1; vs < 4; vs++) {
        iMovie = moviesList[vs];
        if (!iMovie) {
            break;
        }
    
        loopView[vs] = Ti.UI.createView({
            _iMovie : iMovie
        });
    
        loopView[vs].addEventListener("click", function(e) {
            var mv = e.source._iMovie;
            Ti.API.info("Movie: " + mv);
            if (mv) {
                // do something
            }
        });
    }