Reputation: 552
Is it possible in Titanium to have one eventListener for 2 objects? I.e. I have 2 buttons and i want same actions on click.
Should i create: button1.addEventListener
and button2.addEventListener
?
Or
i can make something like:
var array = [button1, button2];
array.addEventListener... ?
Or
maybe i can make something like object.addEventListener('button1_clicked','button2_clicked', function() {});
Upvotes: 2
Views: 1028
Reputation: 5332
Yes. You should create event listeners for each object. For that you should create a function and you can use it to handle your events. Please have a look at following example
button1.addEventListener('click', showMessage); //Adding event handlers to button1
button2.addEventListener('click', showMessage); //Adding event handlers to button2
function showMessage(event){
alert("You have clicked " + event.source.title + " button");
//event.source denotes the control which fired the event
}
Here I have used the same functon showMessage()
to handle your click event. On click of each button, it will display a message which tells the button which you clicked.
If you have many buttons which is used for same purposes, you can try the following
var button = [];
var totalButtons = 10;//I'm assuming you have 10 buttons in your screen
for(var index=0; index<totalButtons;index++){
button[i] = Ti.UI.createButton({
title : 'Button ' + (index+1),
width : 20,
height: 50,
});
button[index].addEventListener('click', showMessage);
win.add(button[index]);
}
Upvotes: 2
Reputation: 6095
Just add the same function to each object. For example, assuming you have two buttons named button1
and button2
:
function myEventListener(e) {
alert('Clicked button with title '+e.source.title);
}
button1.addEventListener('click', myEventListener);
button2.addEventListener('click', myEventListener);
Upvotes: 1