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!!
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.
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);
});
}
精彩评论