Event Listeners for Dynamically Created Buttons
I'm creating a bunch of views dynamically like this:
var views = [];
for (var c=0; c < 3; c++) {
views[c] = Ti.UI.createView({ ... });
var myButton = Ti.UI.createButton({ ... });
views[c].add(myButton);
}
I want to have an event listener on each instance of myButton that gets created:
myButton.addEventListener('click', function(e){
//How do I reference that button?
});
How do I do that? Does the listener have to be inside the view creation loop? Or do the buttons need to be arrays like the views (e.g. myButton[c])?
I'd appreciate any help.
5 Answers
-
You need to use the event's source
myButton.addEventListener('click', function(e){ // e.source is the event's source e.source.title='This is the button you just clicked' });
-
Not sure if this is even relevant to the user, but maybe for someone else looking for an answer…
You need to create two functions, an event handler creation function and the function that creates the dynamic assets (views, buttons, etc).
So..
function createHandler(obj) { obj.addEventListener(eventType, function); } function createViews(num) { for(var i = 0; i < num; i++) { var tempObj = Ti.UI.createSomething({ prop:val, prop:val }); createHandler(tempObj); someParentWindow.add(tempObj); } }
Works perfectly for me.
-
Hi Clifton-
I'm currently using the following code in a project. It works. However, I feel your pain about Events, they do not bubble correctly and get lost. In my opinion the less nesting of views the better.for (var i = 0; i < galleryImages.length; i++) { var iView = Ti.UI.createImageView({ backgroundImage:galleryImages[i], width:minWidth, height:minHeight, top:0, left:0, backgroundColor:"#30333333", visible:true, touchEnabled:true, zIndex:i+1 }); iView.addEventListener("singletap", OPEN_ITEM); thumbnailContainer.add(iView); items.push(iView); } function OPEN_ITEM(e){ //== access your object via e.source }
Titanium could be a very efficient tool if they get Events and zIndex working correctly.
-
I agree with Jag, that code should work. Your OPEN_ITEM function needs only to access the object's properties using the 'source' method, i.e.
function OPEN_ITEM(e){ //== access your object via e.source var clickedView = e.source; Ti.API.info(clickedView.backgroundImage); }
I have had a situation where in Android the only iteration that works is the last one, however this was in an older version of the framework. I got around that by adding an key/pair to an array within my for loop, and then access the property I wanted out of the array. Not ideal but it did work.
-
This was a great help, thanks!