There’s no place like ::1

Titanium With Coffeescript and Backbone.js

| Comments

I’ve been doing a lot of Titanium Mobile development lately. In my quest of getting more efficient doing it, I think I finally found a sweet spot that allows me to concentrate on implementing features, and not fight with Titanium and CommonJS modules.

This is part 1 of this post. I will cover how I use CoffeeScript with Titanium and automate stuff. On part 2 I will talk about how Backbone.js was the best thing I could add to my Titanium project… yet :)


I personally dislike the Javascript syntax, and although I don’t think CoffeeScript is the holy grail, I think it does a pretty good job of hiding the pieces I hate. I really feel 2 or 3 times more productive when writing CoffeeScript. So I had to integrate it with my Titanium projects.

OTOH, I only use Titanium Studio when I really have to. Otherwise, I do my daily code on the CLI with Vim and tmux. That meant I had to come up with a solution to run Titanium projects from the CLI. I quickly found some random Gist with the instructions to do that. (some weeks ago, Matt Apperson launched his MakeTi tool too, it is worth checking out).

So I wrote a Rakefile. You’ll notice it’s a very lazy one, because most of the values I hardcoded could be derived by inspecting the XML files on the project. But it does the basic job.

Wiring it

So you’ve noticed the coffee command on line 19? That’s where the magic happen. So let me quickly explain how I organize the skeleton of an app. I useually create an empty Titanium project, add the Rakefile, and then create the following structure:

Let me break files 1 and 2 individually:

1 - app.js

This will be the only Javascript file I will need to write. The contents? Just create the main namespace for the app (more on that later) and include the generated main.js file!

The Resources/js/main.js file is derived from the coffee/ fill we will now write.

2 -

On this CoffeeScript file, I start by including other classes that I will need, and bootstrap the application. Example:

So the final question is, how do I create and manage a “view controller”?

Building View Controllers

I love to use CoffeeScript classes to build “view controllers” around a window. I usually build a class for each window, and some times one class for each specialized view. A typical view controller class would be like this:

So notice how I encapsulate the logic into one class, and then store a reference to the class on the global app scope. This is probably bad practice because of CommonJS and stuff, but I found it is the best compromise for me, and it makes me really focus on the code itself.

So what about modules, Backbone.js and network operations? Stay tuned for part 2 of this module where I talk how I use Backbone.js for REST operations and view bindings.

UPDATE: Part 2 is online