开发者

attaching an array to an event in javascript?

开发者 https://www.devze.com 2023-02-08 10:25 出处:网络
var image = []; for (var i = 0; i < test.length; i++) { image[i]= Titanium.UI.createImageView({ top: row,
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);
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消