Join Rafael Hernandez for an in-depth discussion in this video Handling touch events, part of Up and Running with Titanium.
If you want your application to be interactive, then you've got to create a way for users to interact with your display objects. Thankfully, Titanium features a rich and robust event system that lets us listen for multiple user interactions on display objects. I'll add a button to the application by creating a variable called btn. I'll set this equal to ti.ui.createButton. For the argument, right now, I'll pass an empty object. A button is almost similar to a label object except that the text will use a property called title.
I'll style the font. Styling the text of a button is similar to styling text of a label. I'll set the size. I'll set the weight. Then, I'll set the font to be used with conditional logic. Lastly, I'll set the width of the button to auto so that it auto-sizes with the text. So that we can see the button on the screen, we'll add it to the window. To listen for events on display objects, we'll use the objects add event listener function. The event that we'll listen for is the click event. The second argument is a function to fire once the event has been heard by the object.
I'll create an anonymous function and pass a variable e which represents the event that was heard, and is subsequently passed to the function. Our goal here will be to change the title of the button with each tap. To access the button indirectly, we'll use the source property of the event object. Then, indirectly accessing the object, we'll use the title property. This is the title property of the button. Each time the button is tapped, we'll append to the button title, was tapped. Then, because we're updating the text of the button, we need to also update the width.
We'll reset the width to auto. In case you're wondering why we don't access the button by using the variable btn, it's so that we don't inadvertently create a memory leak. In general, it's a good idea to try not to reference objects directly from within other functions. So, whenever you can, you want to access objects via some indirect method. Like using the source property of the event object, in this case. Let's take a look at the project in the simulator. You can see the button at the center of the screen each time the button is tapped, the text was tapped, is added to the button.
We can keep doing this on and on, and eventually the text will truncate and we won't be able to see the additional text that's added. As you implement event listeners on your display objects, remember that you can check the documentation for other events that you can listen for.
- Setting up Titanium Studio
- Creating a new project
- Adding interactivity
- Using CommonJS modules
- Including platform-specific code
- Creating a preferences panel
- Making cross-platform adjustments