0
var image = [];

for (var i = 0; i < test.length; i++) {         
    image[i]= Titanium.UI.createImageView({ 
        top: row,
        image: avatar                                
    });             
    win.add(image[i]);
}

image[i].addEventListener('click', function (e) {
    alert('image number'+i);
});

im trying to attach an event to an array, but its saying object unidentfied! :)) whats wrong!!

3
  • Where is it saying object undefined? Commented Feb 4, 2011 at 23:06
  • 1
    Did you mean to have the addEventListener call outside of your for loop? As written, you are accessing an undefined element of your image array. Commented Feb 4, 2011 at 23:07
  • yeh i want outside, if put it inside it will assigned to the last element! Commented Feb 4, 2011 at 23:15

2 Answers 2

2

This is actually no new solution, just a correction for @Mahesh Velaga's answer:

var image = [];
for (var i = 0; i < test.length; i++) {         
    image[i]= Titanium.UI.createImageView({ 
        top:row,                 
        image:avatar                                
    });             
    win.add(image[i]);

    (function(i) {  // -- added (inti)

        image[i].addEventListener('click', function (e) {
            alert('image number'+i);
        });

    })(i);          // -- added (inti)
}

You need a closure around the eventListener for the i value to be local for its callback.

Sign up to request clarification or add additional context in comments.

Comments

1

Your variable i is out of index

There is no image[test.length] and hence it throws the error (since i = test.length once the loop is exited)

Edit:

Try the following:

var image = [];
for (var i = 0; i < test.length; i++) {         
    image[i]= Titanium.UI.createImageView({ 
        top:row,                 
        image:avatar                                
    });             
    win.add(image[i]);
    setEventListner(i);
}

function setEventListener(index) {
    image[index].addEventListener('click', function (e) {
         alert('image number'+ index);
    });
}

4 Comments

The solution would appear to be to move the event listener attachment inside your loop...
yeh i want outside, if put it inside it will assigned to the last element!
what do you mean by "if put it inside it will assigned to the last element!" ? You are adding a different event listener to each image, if you put it inside the loop.
There is still a problem with this. The for loop does not create a closure, so the i variable inside the eventListener will be global, and will always say the last value it was given. This is pingpong's problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.