We have been using Titanium to build mobile apps for some time now. It is truly amazing how much more productive we are as opposed to when we use POOC (Plain Old Obj-C). Granted, Titanium is not a great fit for some applications, but for your standard network and data-heavy line of business applications, it rocks.
But, Titanium does not give you a lot of guidance on how you should write your app. They provide all the pieces you need, but folks are still figuring out the best way to structure things. So, we thought we would show you our particular technique for putting together a Titanium mobile app.
coffee -w -c *.coffee in whatever directory your files are in, and it continually watches for any changes and immediately compiles the
*.coffee into a
*.js file.) So to be clear, you are only ever referencing the .js files in your Titanium project, Titanium doesn’t know anything about CoffeeScript or how to parse/use it.
1 2 3 4 5 6 7
Another thing CoffeeScript enables, is an easier-on-the-eyes way to creates “classes”, for example (from the CoffeeScript docs):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
(If you really want to see what that gets translated to, put on some shades and click here)
main file, which sets up the main tab group and kicks everything off.
1 2 3
In the generic_window.coffee file, we create a class definition for a generic window, and actually create a Titanium window in the constructor. We then attach the class definition to the root object so we can get at it from anywhere.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Now the main file sets up the tabgroup, and actually instantiates some windows from the above generic window class…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Now, let’s add a custom property to our generic window class, so add this line to the constructor of generic_window.coffee:
This creates a property and gives it a default value. To access it, you could say
root.Win1.custom1. Now let’s add an event handler that displays an alert box containing the value of
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
If you would like to see how it all hangs together, clone the GitHub repo here and try it out. The bottom line is that before CoffeeScript, our Titanium apps tended to resemble spaghetti, but now we are able to encapsulate functionality and just generally make things look much cleaner. Sure, you don’t need CoffeeScript to do this, but it sure makes it a lot more fun!