view in scrollableView bug
Hello,
I have a loop creating views on the fly and adding them to a scrollableView.
I've added an eventlistener when clicking on the view and trying to return the view Object, instead I get the imageView object.
Any idea what I'm doing wrong here please?
for(var i in list)
{
if(list[i]){
var view = Ti.UI.createView();
var imageView = Ti.UI.createView();
view.add(imageView);
view.addEventListener('click',function(){
return function(e){
Ti.API.info(e.source); // returns the imageView object!!
};
}());
}
}
2 Answers
-
Accepted Answer
Bruce
Is the code you have provided copied straight out of your project? If so, there are a couple of observations I've made:
Although the imageView variable name implies that you are intending to create an image view, you actually create a view, Ti.UI.createView(). Isn't Ti.UI.createImageView() what you really want?
Your event listener may work how you intend, but it's not in a format that most people use.
Please see below for a revised version of your code that takes these points into account:
for(var i in list) { if(list[i]){ var view = Ti.UI.createView(); // note, creating an imageView var imageView = Ti.UI.createImageView(); view.add(imageView); imageView.addEventListener('click',function(e){ // note the simpler format of addEventListener Ti.API.info(e.source); }); } }
You can indeed disable touch events on the view, as you suggest in your answer but, then, you will be unable to listen for any other events that it receives. Furthermore, in your code you create a separate listener at each iteration of the loop. You could instead make use of event bubbling to simplify the listeners, thus creating only one:
var containerView = Ti.UI.createView(); for(var i in list) { if(list[i]){ var view = Ti.UI.createView(); var imageView = Ti.UI.createImageView(); view.add(imageView); imageView.addEventListener('click',function(e){ Ti.API.info(e.source); }); imageView.customName = "anImage"; containerView.add(view); } } containerView.addEventListener('click',function(e){ if( e.source.customName === "anImage" ){ Ti.API.info("You clicked image: "+e.source); } }); win.add(containerView);
Note that this code hasn't been tested, but you get the idea! :)
-
Arg found the solution, touchEnabled on the imageView to give priority to the View.