0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Aqeel Ashiq
  • 1,988
  • 5
  • 24
  • 57

2 Answers2

1

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
        }
    });
}
Anand
  • 5,323
  • 5
  • 44
  • 58
0

Well, first I'll start that what you are doing in the code above could potentially cause a memory leak since you are holding a reference to the iMovie variable.

what you should try doing is:

var mv = e.source;

this will return the source object that fired the click event.

developer82
  • 13,237
  • 21
  • 88
  • 153