pingpong
pingpong

Reputation: 1247

locating images on a for loop, and then adding an event?

i have this scenario where im loading images using a for loop:

for (var i = 0; i < test.length; i++) {

 var likeImage= Titanium.UI.createImageView({
    image:'like.png',
    width:17,
    height:10,
    left:110,
    top:4
});

}

then im adding an event, if the one of the hearts is clicked it should change image.

likeImage.addEventListener("click", function(e) {

likeImage.image = 'unlike.jpg';

});

but when i click nothing is happening, can anyone shed light on this problem please, thanks guys

edit:

 tableView.addEventListener('click', function(e) {
var tappedRow = e.row;


                    alert(tappedRow.username1.text);

                });

but its giving me an erro, saying this is not an object! or unidentified!! thanks

Upvotes: 0

Views: 460

Answers (3)

Aaron Saunders
Aaron Saunders

Reputation: 33345

EDIT --

After looking at all the code,

http://paste.bradleygill.com/index.php?paste_id=152785

you dont need to put a click event on the image, put the click event on the tableView and the "event.source" will be the object that received the click.

if the object that received the click is one of your "likeImages" then change it to unlike or whatever else you want to do

Upvotes: 2

gion_13
gion_13

Reputation: 41533

refer to the image object through this. when the event handler is triggered, your likeImage may not even be defined anymore or can point to another object while the this keyword will always point to current object in a function/object. so you should do

likeImage.addEventListener("click", function(e) {
    this.image = 'unlike.jpg';
});

in your code, you declare var likeImage in the for scope (not the global one) and you redeclare that variable in each loop's iteration, so your variable likeImage is holding a reference only to the last image object created.
For example, after the execution of the loop, the variable a will always be equal to 9 :

for(var i=0;i<10;i++)
    var a = i;
alert(a);

Upvotes: 0

Fran Verona
Fran Verona

Reputation: 5476

Try to use 'this' instead of likeImage:

likeImage.addEventListener("click", function(e) {

    this.image = 'unlike.jpg';

});

Upvotes: 0

Related Questions