Appcelerator Developer Blog

Getting To Know Alloy (Part Two)

The following is the second in a series of in-depth posts introducing developers to Alloy, the new MVC framework for Titanium. The previous article in this series can be found here.

Last time, we discussed some of the architectural concepts around Alloy, and walked through the creation and structure of a new project. In the posts to follow, I would like to focus on the model, view, and controller tiers of Alloy as we build out a simple TODO list application.

Creating Alloy “Views”

In the simple Titanium project we generated last time, a fresh Alloy project was generated in the “app” folder in our Titanium project root:

The “app” directory contains all of our application code and other resources (except internationalization files, which still reside in the [project root]/i18n directory). When we ran the project last time, Alloy’s compiler generated the contents of our [project root]/Resources directory, including modifying Resources/app.js with logic that will initialize and display our application.

Alloy View XML and the Root Component

An Alloy application is composed of numerous self-contained components, but we need one top level component to render the rest of the application. The first component Alloy will display is represented in app/views/index.xml. Initially, this file should contain something similar to the following:

<Alloy>
	<Window class="container">
		<Label id="label" onClick="doClick">Hello, World</Label>
	</Window>
</Alloy>

Inside the top-level Alloy tag, there are child tags which should be familiar to Titanium developers as UI controls in the Ti.UI namespace in the standard Titanium API. Alloy has created a declarative markup for the same type of view hierarchy you would manually construct in JavaScript.

The above could also be expressed (in app.js in a standard Titanium app) with something akin to the following (minus any event handling):

var container = Ti.UI.createWindow(),
    label = Ti.UI.createLabel({
        text:'Hello, World'
    });
 
container.add(label);

Titanium Style Sheets

The Alloy view XML (usually) only represents the hierarchical structure (and content) of the view. The styling and object properties are declared in Titanium Style Sheets (TSS), which are a derivative of JSON. TSS gives us three very powerful features to style the components in our view, which are very similar to the equivalent functionality in CSS:

Style by ID

Using a hash to identify a specific control, we can specify properties we want to assign to a single control within our view hierarchy:

"#aSpecificView": {
	backgroundColor:"white"
}

Style by Class

Using a leading dot to identify a “class” of controls, we can specify properties we want to assign to multiple controls within our view hierarchy:

".someSharedProperties": {
	width:Ti.UI.SIZE
}

Style by Control Type

Using the name of a Ti.UI control, as either a quoted or non-quoted string, we can apply a set of properties to all UI controls of a certain type that are created:

Label: {
	textAlign:'center'
}

In the default application, app/styles/index.tss contains the following style declarations:

".container": {
	backgroundColor:"white"
},
 
"Label": {
	width: Ti.UI.SIZE,
	height: Ti.UI.SIZE,
	color: "#000"
}

If we add these styles to our Titanium JavaScript example from before, it would look something like:

var container = Ti.UI.createWindow({
        backgroundColor:'white'
    }),
    label = Ti.UI.createLabel({
        text:'Hello, World',
        width: Ti.UI.SIZE,
    	height: Ti.UI.SIZE,
    	color: "#000"
    });
 
container.add(label);

Building a simple TODO UI

To illustrate how the view tier of an Alloy application works, I’ve begun implementing a TODO list sample application, based on Addy Osmani’s useful Todo MVC project, which compares client side MVC frameworks in the browser. Since Titanium is built primarily for native apps on touch devices (which will probably have at least some platform-specific UI), this won’t be a 1:1 port. But hopefully, it will give you an idea of how to approach this common sample application using Alloy.

Check out the code for the app below on GitHub.

I won’t go through the code line-by-line, but I would like to call out a few of the highlights. The first thing you’ll notice from the screen capture above is the differences in UI. On iOS, we make use of a standard Cocoa Touch toolbar component. On Android, those same options are exposed when the “menu” button is pressed.

In a standard Titanium application, you would include boolean logic in JavaScript to create one set of UI components per platform. Also, you would write code to add an event listener to the activity object of a Titanium window, and programmatically build out the Android menu. Alloy has provided an easier API to accomplish both of these tasks. Let’s first take a look at index.xml, which defines the overall UI structure for the application:

<Alloy>
    <Window>
        <Menu platform="android">
            <MenuItem title="Show All"/>
            <MenuItem title="Show Active"/>
            <MenuItem title="Clear Completed"/>
        </Menu>
 
        <View id="formContainer">
            <Require src="form"/>
        </View>
        <View id="listContainer">
            <Require src="list"/>
        </View>
        <View id="rule1" class="rule"/>
        <View id="rule2" class="rule"/>
        <View id="bar"/>
        <View id="toolbar" platform="ios">
            <Require src="toolbar"/>
        </View>
    </Window>
</Alloy>

The first thing you’re likely to notice in this example is the platform property. In every UI tag provided by Alloy, you can specify a platform property on an XML node, which can be “ios”, “android”, or “mobileweb” currently. When the Alloy compiler is run, the code generator will skip those portions of the view XML altogether, resulting in no Android code shipping on iOS, and vice versa. It also provides a nice, declarative way to specify how the app will be structured differently on one platform versus another.

The second thing you’re likely to notice is the new “Menu” and “MenuItem” tags. This is a special Alloy-specific feature which abstracts away the details of the Titanium API for Android menu creation (Android activities and lifecycle events, etc). Using this syntax, you can create the menu UI and specify event handlers just like you would any other Alloy components.

The other item I will point out in this example is the use of the Require tag. To break up your application into smaller components, you can generate new view/controller/style triads from the command line using alloy generate controller [name of component]. This will create a new view XML, TSS, and controller file which you can use to implement a new subsection of your application. To insert on of these components into the application, you can use the Require tag as in the example above, passing in the controller name as the src property.

You can programmatically create view/controllers as well using something like var myController = Alloy.createController('someController') in JavaScript, which will return an instance of a controller object. To get the Titanium view proxy object which represents the root of the view hierarchy in the view/controller, you will use myController.getView()

One other thing to point out in this first version of the TODO list application is the use of a shared TSS file for the entire application. [project root]/app/styles/app.tss contains shared style classes and Component-level style declarations you’d like to use across the entire app:

Window: {
    backgroundColor:'#fefefe',
    exitOnClose:true,
    navBarHidden:true
},
 
Label: {
    color:'#000'
},
 
'.dottedLine': {
    backgroundImage:'/dots.png',
    backgroundRepeat:true,
    height:'1dp',
    bottom:0,
    opacity:0.3
}

One other thing that may be slightly confusing is the opening/closing of windows. Alloy creates a view hierarchy for you, but does not automatically “open” Titanium windows. In index.js, you’ll notice the only line in that controller file (for now) is a call to open the root window of the application. You must still (for now) handle this in JavaScript while using Alloy.

Clone this TODO sample application and step through the code, beginning with index.xml, index.js, and index.tss. From there, start drilling down into the required components to see how the UI for this application is structured. In the next post in this series, we will dive deeper into the model and controller tiers of the application to see how we approach event handling and data access, to get a full view of what Alloy brings to the table.


Titanium SDK/Studio 3.0.0 Beta Now Available

We want your feedback early and often, and your input helps ensure we deliver the highest quality software possible. Today we release a beta of our 3.0.0 release–the newest version of our Titanium platform. Apart from the hundreds of fixes and improvements we’ve made since version 2.0, we have a number of new exciting items for you to try. From on-device debugging to a much simpler way of constructing your Titanium applications, we’ve got plenty to explore. Read on below, and for full information, please see the release notes.

Note: This is a beta release, and as such may contain regressions or other issues. Please do not use it in production, and keep backups of all important projects and data. We will follow with additional releases in the coming weeks. If you find an issue, please report it in JIRA with a reproducible test case.

How to Update

These are links to continuous integration builds. To install them, choose “Help Menu > Install Specific Titanium SDK…” from inside Titanium Studio.

To update Studio, please visit http://preview.appcelerator.com and follow the instructions to update to the RC stream, or to download a new install.

New Features in Titanium SDK 3.0.0

The docs are all available at: http://docs.appcelerator.com/titanium/3.0/

On-Device Debugging

This release adds support for on-device debugging on Android and iOS. For iOS, on-device debugging requires that both device and the computer running Studio are on the same Wi-Fi network. On Android, debugging takes places over a USB connection.

Alloy Framework

This release coincides with the release of the Alloy, a model-view-controller (MVC) framework for Titanium. Alloy is installed automatically if you install Titanium Studio 3.0. If you’re using Titanium from the command line, you can install Alloy manually using npm.

Titanium Command-Line Interface

This release includes a preview of a new, Node.js-based command-line interface, titanium, intended to replace the Python titanium.py and and builder.py scripts. For this release, some tasks are delegated to the Python scripts, so Python is still required to build projects. If you are installing Titanium Studio, the new CLI is installed automatically. If you are using Titanium from the command line, you can install the new CLI using npm.

Event Bubbling API Changes

This release adds several features to allow more control over event bubbling, as well as more transparency over how bubbling works.

Android Action Bar Support

This release includes partial support for the Android action bar element. In particular, we support tab groups displayed using action bar-based tabs, optional menu items can be displayed as action items in the action bar, and expanding and collapsing action items are supported. There are some additional features being added here now.

Accessibility Features

This release includes support for voice-over accessibility features on iOS and Android. All view elements support a set of new accessibility properties, which can be used to specify the voice-over text associated with a given UI element.

New Features in Titanium Studio 3.0.0

One of the major differences with version 3.0 of the Titanium SDK is that a number of projects come as node modules. Studio will look for a Node.js installation on your system. If it does not find it, it will install it, and then prompt you to install the necessary modules via NPM.

Performance Improvements

We’ve made substantial improvements in the editing speed of our JS, CSS and HTML editors.

Alloy Integration

Create, compile and run alloy projects. Add widgets to existing projects. New integration makes working with alloy projects easy and simple.

Node.ACS Integration

Create, test and deploy new Node.js-based cloud services from inside Studio. Simplified workflow makes it easy to test both client and server locally.

On-Device Debugging

Together with the new Titanium 3.0.0 SDK, you can now debug on your Android or iOS device (Android via USB, iOS via WiFi).

Deprecation Warnings

Is the code you are using deprecated in the current version of the SDK? New warnings will help guide you to what needs refreshing.


Learn more about AT&T’s new Titanium Module

Guest Post – Kevin Griffin, AT&T’s Developer Program

Learn more about AT&T’s new Titanium Module 
Webcast – Thursday 11/15 at 10:00am PT

We at AT&T are very excited about our recent integration with the Titanium platform. Join us on Nov 15 to learn how to easily integrate AT&T APIs using the Appcelerator Titanium module
for the AT&T API Platform
to enable new capabilties into your mobile apps, such as: Speech transcription, in app messaging, location, payment, and more!

This one-hour webcast is a great introduction for Titanium platform developers and existing AT&T API Platform users. We will demo the Titanium module for AT&T APIs as well as give a
quick overview of AT&T API Platform, tips, known issues and Q&A. Also, live attendees will be eligible for a chance to win a smartphone!

To learn more and register for the webcast, visit developer.att.com.

Kevin Griffin, Technical Business Development, AT&T Developer Program
Kevin is chartered with directing the distribution of AT&T’s APIs to the most popular developer’s tools


Get FREE Entry to BB Jam Asia (and Become Eligible for a Free BB 10 Alpha Device!)

BlackBerry is inviting Titanium developers to register for BlackBerry Jam Asia for free! Go to http://www.blackberryjamconference.com/asia and use promo code CJAG65 to get your free registration.

BlackBerry Jam Asia is in Bangkok, Thailand on November 29-30th.  Join this showcase for mobile application developers that focuses on the bold, new direction BlackBerry® is heading with the upcoming BlackBerry® 10 platform.

As an added bonus, RIM is giving away BlackBerry 10 Dev Alpha devices to qualified developers attending BlackBerry Jam Asia! The BlackBerry 10 Dev Alpha device is a prototype device created for the purpose of testing BlackBerry 10 applications during development, and has been created exclusively for developers to help them prepare for the launch of the upcoming BlackBerry 10 platform.

Appcelerator will conduct a breakout session, “Developing Titanium Apps for BlackBerry 10” to discuss how to create new apps or port your existing apps to the BlackBerry 10 platform.

For more information, visit http://www.blackberryjamconference.com/asia/event-info/device.


Getting To Know Alloy (Part One)

The following is the first in a series of introductory posts introducing developers to Alloy, the new MVC framework for Titanium.

A constant request we’ve heard from our developer community, almost since the inception of Titanium, is guidance on architecture and code organization in Titanium apps. As a platform, Titanium provides cross-platform, high level APIs for animation, UI creation, data access, and the core functionality found in native mobile applications. However, historically, Titanium has not been opinionated in how developers structure their JavaScript applications. This has proved to be positive in the sense that we could focus on surfacing lots of functionality from the underlying platforms, but somewhat negative in that developers (particularly those new to large JavaScript programs) sometimes created application structures that were difficult to maintain and potentially inefficient.

It was decided that Appcelerator needed to provide developers with a predictable project structure, based on established best practices we’ve learned from developing hundreds of Titanium applications. Further, we wanted to provide a framework that could give developers better building blocks for rapidly developing non-trivial applications on top of Titanium, and speed up development overall. Alloy was created to accomplish these goals. To hear more about Alloy from lead framework developer Tony Lukasavage, check out his session at this year’s Codestrong conference:

The team at Appcelerator is really excited about Alloy and the benefits it can provide to our developer community. We’re generating docs, tools in our IDE, and advanced technology to fully integrate Alloy into our platform. However, the “old way” of developing Titanium apps will continue to be supported – we think that maintaining a flexible low-level API is important as well. But for many developers, Alloy represents a new (and improved, IMHO) API for serious Titanium app development. As such, I would like to give our developer community an in-depth look at this new framework over the course of a few posts here on the dev blog.

In this post, we will explore the basic architecture of Alloy, and how Alloy is actually implemented. We will also generate a new Alloy project, and explore what you get “out of the box”. In our next article, we will actually dig in and start writing some code for the seminal TODO-list application demo. NOTE: This tutorial assumes an OS X operating system already configured for Titanium development, but these steps should be pretty easy to reproduce on Windows as well.

Key Architectural Concepts

Alloy is a “component-oriented” application framework that enforces separation of concerns with a Model/View/Controller architecture. Let’s take a look at some of the core architectural concepts for Alloy.

What does “component-oriented” mean?

Alloy applications are designed around reusable components that form the building blocks of your application. A “component” in an Alloy application is a CommonJS module generated from the XML, styles, and JavaScript controller logic written by developers. Most often, these components will be developed specifically for a given application, but Alloy also provides the ability to create reusable components that can be easily shared across applications (called “widgets” by Alloy). Components are responsible for responding to user interaction with UI objects under their control, and for managing and updating their own internal state. Components can be nested within one another, and do not need knowledge of the application’s global state (or at the very least, a very small amount of knowledge of the global state of the app).

Components can be created both in XML markup and programmatically, as we will see in this tutorial series.

Model/View/Controller

The Model/View/Controller (MVC) design pattern is one of the most widely implemented patterns in professional software development. In brief, MVC promotes the separation of data representation, often a graphical user interface (the view), and domain-specific business logic (the model). The “traffic cop” that interacts with data and updates the view is called the controller. Alloy provides facilities for structuring your application code in this way as well.

The Model Tier

The model tier of an application implements business logic, like saving an “order” object or updating an “employee” object in some kind of data store. In Alloy, special JavaScript files contain model logic for persistence using a common interface.

The View Tier

The view tier of an Alloy application is coded with a combination of a Titanium-specific XML dialect and styles provided in Titanium Style Sheets (TSS). XML markup is used to declaratively create a user interface, and define the structure of a component in the application. Since Titanium is a cross-platform development environment, and developers will need to support multiple device types and form factors, we needed to provide an easy mechanism for developers to alter the style and attributes of their components based on platform and screen size. TSS provides a CSS-like mechanism for declaring object properties and styes, optionally customized for different platforms and screen sizes. TSS is a derivative of JSON, so style declarations can contain nested objects, values, and arrays.

The Controller Tier

A JavaScript file is paired with an XML/TSS component declaration to respond to user interaction, handle events, and potentially provide a public interface to work with the internal state of a component. The controller will interact with the model to execute business logic, and update the view of the component as appropriate.

Alloy Project Tour

Now that we understand some of the architectural concepts behind Alloy, let’s dive into an actual Alloy project and explore what’s going on.

Alloy has two primary components – a runtime JavaScript library which is actually executed on the device, and a set of build/compile commands which generate Titanium JavaScript code from declarative markup and TSS styles. Alloy’s compile command is executed before the main Titanium build process is initiated, so much of the “magic” of Alloy happens before your app even makes it onto the device. The Alloy compiler must be installed first before an Alloy app can be created.

Alloy’s compiler and code generators, along with many other build tools at Appcelerator, are now built on node.js – node provides a standard library and CommonJS-based runtime for JavaScript applications outside the browser, and has found widespread use as an option for server-side programming. In this tutorial, we will be working with node, Titanium, and Alloy exclusively from the command line. More information on using Titanium from the command line can be found here.

If you haven’t done so already, download and install node.js. This will set up both the “node” and “npm” commands on your system path. To install the Titanium CLI via npm (the “node package manager”), open a terminal and execute:

sudo npm install -g titanium

To install Alloy, use:

sudo npm install -g alloy

These commands should have now set up “titanium” and “alloy” commands on your system path. Next, generate a new Titanium project, which we will enable as an Alloy app in the next step:

titanium create -d . -n AlloyTest

This will create a new Titanium project in the current working directory. Answer the questions as prompted, and change into the new project folder you just created. Inside this folder, you should find the familiar tiapp.xml and Resources directory typically found in a Titanium application. Just to make sure everything has been created properly, you might try running the generated application on the simulator:

titanium build -p ios -F ipad

To “Alloy enable” this application, we will use the “alloy” command we installed via npm just moments ago:

alloy new .

Listing the contents of the project directory should now reveal some new items:

  • The “app” directory, which is where we will write our JavaScript application code going forward
  • The “plugins” directory, which now contains a ti.alloy compiler plugin
  • A “physical size” native module for Android



Also, you’ll notice Alloy has updated your app’s tiapp.xml file to include the compiler plugin and native module configuration it needs.

The “app” directory contains subfolders for your application code, styles, images, and anything else you’d like to ship with your application. In standard Titanium projects, these types of things would go in the “Resources” directory – with Alloy, the contents of the Resources directory are generated dynamically at compile time. This allows for optimizations such as removing platform-specific code that will not be used.

The subdirectories of the “app” directory organize the constituent elements of your application:

Special Directories

  • The “views” directory contains the structural declarations in XML of your app’s components
  • The “controllers” directory contains the behavior code for your app’s components
  • The “models” directory contains business objects used for persistence and data access.
  • The “styles” directory contains Titanium Style Sheets for your app’s components.
  • The “assets” directory is meant for images and other non-code resources for your application. In practice, the contents of this directory are actually directly copied over to the Resources directory.

Special Files

  • “config.json” at the top-level directory allows developers to specify configuration parameters targeted at either development or production environments.
  • “styles/app.tss” is a global, shared TSS file for your entire application. This is a great place to define default styles for built-in UI controls and shared style classes.


Let’s build and run our project again:

titanium build -p ios

You’ll notice that the default splash screen and app have been replaced with an Alloy-branded splash screen and a simple “Hello World” label. If you inspect the contents of the “Resources” directory, you’ll notice that there’s now a “Resources/alloy” directory, which contains the runtime library for the Alloy framework, and a “Resources/alloy/controllers” directory where Alloy has generated Titanium JavaScript API calls based on the XML and TSS declarations in the “app” directory.

Next time…

In the next installment of this series, we will explore the “view” tier of an Alloy application in depth, and understand how to declaratively (and programmatically) create user interfaces in Alloy.

Page 13 of 90« First...1112131415...203040...Last »