EventListener not attaching in a loop
I am pulling my hair out with (what I am sure is a simple) problem.
I have the following code:
var favorite = Titanium.UI.createImageView({
image:'images/favorite-off.png',
width: 34,
top:20,
right:30,
height:30
});
(function(){
var loopFavorite = favorite;
favorite.addEventListener('click', function(e) {
loopFavorite.image = (loopFavorite.image == 'images/favorite-on.png') ? 'images/favorite-off.png' : 'images/favorite-on.png';
});
})();
The issue is that the click event never fires. No matter what code I put in the listener. (e.g. Ti.API.info('test');).
This is in a for loop so I have put it in a closer, but still nada. The crazy thing is that in the same for loop I have a listener that is firing just fine.
I am adding the favorite to the table row later in code, in case you think that is the issue. The image shows up as expected, just the event listener does not seem to attach itself.
Any Ideas?
3 Answers
-
It turns out there is some off behavior with the ImageView. At the suggestion of Kevin, I switched it to a standard view and used the backgroundImage property. Everything worked as expected.
-
try to create a favorites array outside of the loop. use code like this to attach an event
favorite[i].addEventListener('click', function(e) {
});
i hope this explanation is of any help to you!
-
Does the event fire when the last image is clicked? Try to pass the var favorite into the function (closure) as following.
(function(favorite){
var loop…})(favorite)