Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Appcelerator Titanium Smartphone App Development Cookbook Second Edition

You're reading from   Appcelerator Titanium Smartphone App Development Cookbook Second Edition Over 100 recipes to help you develop cross-platform, native applications in JavaScript

Arrow left icon
Product type Paperback
Published in Nov 2015
Publisher
ISBN-13 9781849697705
Length 368 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (16) Chapters Close

Preface 1. Building Apps Using Native UI Components FREE CHAPTER 2. Working with Local and Remote Data Sources 3. Integrating Maps and GPS 4. Enhancing Your Apps with Audio, Video, and Cameras 5. Connecting Your Apps to Social Media and E-mail 6. Getting to Grips with Properties and Events 7. Creating Animations, Transformations and Implementing Drag and Drop 8. Interacting with Native Phone Applications and APIs 9. Integrating Your Apps with External Services 10. Extending Your Apps with Custom Modules 11. Platform Differences, Device Information, and Quirks 12. Preparing Your App for Distribution and Getting It Published 13. Implementing and Using URL Schemes 14. Introduction to Alloy MVC Index

Creating buttons and capturing click events

In any given app, you'll notice that creating buttons and capturing their click events is one of the most common tasks you do. This recipe will show you how to declare a button control in Titanium and attach a click event to it. Within that click event, we'll perform a task and log it to the info window in Appcelerator Studio.

This recipe will also demonstrate how to implement some of the default styling mechanisms available for you via the API.

How to do it...

Open your app.js file and type the following code. If you're following along with the LoanCalc app, the following code should go after you created and added the textfield controls:

//calculate the interest for this loan button
var buttonCalculateInterest = Ti.UI.createButton({
   title: 'Calculate Total Interest',
  id: 1,
  top: 10
});

//add the event listener
buttonCalculateInterest.addEventListener('click', calculateAndDisplayValue);

//add the first button to our view
view.add(buttonCalculateInterest);

//calculate the interest for this loan button
var buttonCalculateRepayments = Ti.UI.createButton({
   title: 'Calculate Total Repayment',
  id: 2,
  top: 10
});

//add the event listener
buttonCalculateRepayments.addEventListener('click', 
                          calculateAndDisplayValue);

//add the second and final button to our view
view.add(buttonCalculateRepayments);

Now that we've created our two buttons and added the event listeners, let's create the calculateAndDisplayValue() function to do some simple fixed interest mathematics and produce the results, which we'll log to the Appcelerator Studio console:

//add the event handler which will be executed when either of //our calculation buttons are tapped
function calculateAndDisplayValue(e)
{
   //log the button id so we can debug which button was tapped
  console.log('Button id = ' + e.source.id);

    if (e.source.id == 1) 
    {
       //Interest (I) = Principal (P) times Rate Per Period 
       //(r) times Number of Periods (n) / 12 
       var totalInterest = (tfAmount.value * (interestRate / 
       100) * numberMonths) / 12;
        
      //log result to console
      console.log('Total Interest = ' + totalInterest);
    }
    else 
    {
      //Interest (I) = Principal (P) times Rate Per Period (r) 
      //times Number of Periods (n) / 12 
      var totalInterest = (tfAmount.value * (interestRate / 
      100) * numberMonths) / 12;
      
      var totalRepayments = Math.round(tfAmount.value) +  
      totalInterest;
      
      //log result to console
      console.log('Total repayments' + totalRepayments);
    }

} //end function

How it works...

Most controls in Titanium are capable of firing one or more events, such as focus, onload, or (as in our recipe) click. The click event is undoubtedly the one you'll use more often than any other. In the preceding source code, you will notice that, in order to execute code from this event, we are adding an event listener to our button, which has a signature of click. This signature is a string and forms the first part of our event listener. The second part is the executing function for the event.

It's important to note that other component types can also be used in a similar manner; for example, an imageview can be declared. It can contain a custom button image, and can have a click event attached to it in exactly the same way as a regular button can.

How it works...
You have been reading a chapter from
Appcelerator Titanium Smartphone App Development Cookbook Second Edition
Published in: Nov 2015
Publisher:
ISBN-13: 9781849697705
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image