In the 1st part Using Appcelerator to create your mobile applications - Part 1, we briefly discussed the benefits of creating mobile applications with this technology and explained with an example how to start a project in Alloy MVC. This sample application, which will be called MiBiblioteca, works for Android and IOS thanks to Titanium SDK.
In this second part of our series (as promised in Part 1), we will focus on enhancing the application by incorporating additional books into our mobile library. We'll explore the necessary steps to modify some code, create an array of book objects, and style our application for a visually appealing experience.
To store and manage the book collection globally, we'll define an array of objects in the Alloy.js file. This file, being the first to run in Appcelerator, is the perfect place for initializing global variables. Here's how we define the books
object:
Notice the inclusion of the image
attribute, which stores links to book cover images.
To accommodate the new image
attribute, we need to modify the books.js model by adding a corresponding column:
With the model and global book array ready, we can populate the library by iterating through the array and adding each book to the collection. Here's the implementation:
This for
loop ensures all the books are added to the collection.
index.xml
To display the book title and cover image, we update the XML layout as follows:
Here, we use Label
for the title and ImageView
for the book cover.
index.tss
The styles for the elements are defined in styles/index.tss:
Ti.UI.FILL
ensures the rows span the full width of the device.height
attribute specifies the row height.
To enable interaction, we modify the click event to retrieve the selected book's data using its position in the array:
bookdetails.xml
Add an ImageView
element to display the book cover:
bookdetails.tss
Define styles for the details view:
In the bookdetails.js controller, pass the image URL to the ImageView
:
Using Alloy MVC in Appcelerator simplifies the creation and styling of complex views while ensuring code reusability. As your application grows, leveraging community-developed widgets and modules, such as those found on gitt.io, can greatly enhance your productivity.
Tip: By maintaining a separation of views and functionality, you can support platform-specific designs (e.g., Android and iOS) without duplicating controller logic.