Using CommonJS modules for UI View components in Titanium
I’ve been playing with using CommonJS modules in Appcelerator Titanium to create reusable components and prototypes. I start with a basic object structure:
function Car() {
this.init.apply(this, arguments);
}
Car.prototype.init = function (make, model) {
this.make = make;
this.model = model;
};
Car.prototype.make = null;
Car.prototype.model = null;
Car.createWithMakeAndModel = function (make, model) {
return new Car(make, model);
};
module.exports = Car;
Whilst you may argue there is some redundancy in the pattern I use, I makes sections of code easy to override later on if I decide to use it as a prototype.
You may also frown upon the use of module.exports = Car;. However I find that
var Car = require("Car");
looks and feels better than
var Car = require("Car").Car;
You may argue that you should never have access to the constructor and that you should use factory methods. Whilst your argument is valid, I prefer to be able to make sure that my object X is an instance of Y using the built in instanceof operator.
How this applies to views and windows
For views and windows I add .view and .wnd properties to my object inside my init() method, which is where I call all other parts of my view construction. Take the following example of a list view.
function UIListView()
{
this.init.apply(this, arguments);
}
UIListView.prototype.init = function () {
this.view = Ti.UI.createTableView();
};
UIListView.prototype.populate = function (data) {
var i = 0, len = data.length, row;
for (; i < len; ++i)
{
row = Ti.UI.createTableViewRow(data[i].asTableViewRow());
this.view.appendRow(row);
}
};
module.exports = UIListView;
As you can see I can now call populate() at anytime to update my view with new data.
I’d like to experiment more with patterns like this. I’d love to hear your opinions and suggestions for other patterns or structures, so tweet me or send me an email.
Tutorial: Building a Twitter client with Appcelerator Titanium & jsOAuth - Part 2
Back in Part1 we started to build a alert based twitter client using jsOAuth, a Javascript OAuth library and Appcelerator Titanium, a platform for making applications using web technologies.
In this part, we’ll add better notifications, using Growl, libNotify or Snarl and add a timer to fetch new tweets every 1 minute.
Titanium Notifications
Using the Titanium Notification module we get better looking notifications that come from the system. On OSx Growl is used, On linux libNotify and on Windows Snarl. All will fall back to a basic built in notification system if you don’t have any of those notification systems installed.
To create a notification we need to call Titanium.Notification.createNotification() and then set each of the notification properties. With this we can update our code as follows.
timeline.forEach(function (element){
var notice = Titanium.Notification.createNotification();
notice.setTitle(element.user.name);
notice.setMessage(element.text);
notice.setTimeout(1000);
notice.show();
});
The code is fairly straight forward, we set the title to the name of the person who made the tweet, the message body to the tweet status and then set the notification to display for 1 second (1000 milliseconds).
If you run this code now, your screen will be filled with 20 tweets which clear after a second. This looks much better but a one off hit of statuses isn’t exactly useful.
Timers and tidbits
Next we should implement a timer to check for statuses every 60 seconds. This is done using the setTimeout() function.
Firstly, we need to wrap the body of our API call in a function, that we can call from the setTimeout function.
function updateTimeline() {
oauth.get('http://api.twitter.com/1/statuses/home_timeline.json', success, failure);
}
At the top of our success() function, we add our timeout.
function success(data) {
setTimeout(updateTimeline, 60000);
/* ... */
}
Why do we do this? setTimeout executes a function after the specified delay meaning we could wrap the call in a conditional to prevent the next update. setInterval is a little harder to control because it calls the function every specified interval until we clearInterval.
If you ran this code, nothing would happen. That’s because we didnrsquo;t call updateTimeline() yet. Add the line after the updateTimeline decalration and then launch the app.
function updateTimeline() { /* ... */ }
updateTimeline();
I think you’ll agree, the app has just become far more uselful, but there is one think left. Every minute we get notifications of tweets we’ve already seen, which after a few minutes gets a little annoying. To solve this we can use the since_id parameter.
However, jsOAuth’s get method is a little limited in this version. Instead we’ll switch to the request method, which is far more flexible but more complicated to use.
/**
* Makes an authenticated http request
*
* @param options {object}
* method {string} ['GET', 'POST', 'PUT', ...]
* url {string} A valid http(s) url
* data {object} A key value paired object of data
* example: {'q':'foobar'}
* for GET this will append a query string
* headers {object} A key value paired object of additional headers
* success {function} callback for a successful request
* failure {function} callback for a failed request
*/
As you can see, instead of passing separate parameters, we pass an object of key value pairs to set up the request. All the key names however reflect the naming convention of the get and post methods.
var sinceId = '';
function updateTimeline() {
var params = {};
if (sinceId != '') {
params.since_id = sinceId;
}
oauth.request({
"method": "GET",
"url": "http://api.twitter.com/1/statuses/home_timeline.json",
"data": params,
"success": success,
"failure": failure
});
}
updateTimeline();
The first 4 lines of the updateTimeline function check if we have a sinceId, and add it to the params object. This way we don’t get an invalid signature error from the Twitter API when it looks for the value.
However, at the moment we haven’t set the sinceId, we need to do this in the success() function. The Twitter API returns tweets with the latest at the top, by default. Using this knowledge, we can gleam off the first id and store it in the sinceId variable.
function success(data){
setTimeout(updateTimeline, 3000);
var timeline = JSON.parse(data.text);
if (timeline.length > 0) {
if (sinceId == timeline[0].id) {
return;
}
sinceId = timeline[0].id;
}
timeline.forEach(function (element){ /* ... */ });
}

Launch the Titanium Developer tool and run your app. You’ll see the latest batch of 20 tweets but from then on you’ll only see new tweets until the next time you launch the app.

That’s all there is to it. In only a handful of extra lines of code, we’ve made the app more user friendly and useful.
To extend this app you could add a callback to the notification to allow replies or a menu item to allow posting of new statuses. The possibilities are great and Appcelerator Titanium makes it really easy to build applications quickly using technologies that most people are familiar with.
If you have any questions, comments or ideas on further expansion to this tutorial, please feel free to email or tweet me
Tutorial: Building a Twitter client with Appcelerator Titanium & jsOAuth - Part 1
This tutorial is intended to explain how to use Appcelerator Titanium with a javascript OAuth library, called jsOAuth, along with basic use of the Twitter API
Getting Started
You’ll need to download and install the Titanium Developer tool. There’s a great tutorial “Getting Started” on the Appcelerator Developer site. Feel free to skip this step if you already have the Developer tool installed and understand how it works.
Once you’ve followed that tutorial, set up a new project called “Growl Tweet Notifier” and continue this tutorial
jsOAuth and the Twitter API
jsOAuth was designed to be easy to learn and easy to use, as a result most of the heavy work is done for you. Hopefully you’ll agree how easy it is to use.
Download the latest version¹ of jsOAuth and put it into the Resources/ directory of your project.

You’ll need to reference the library in your project, so go ahead and place the following in your , and update the file reference as appropriate.
<script src="jsOAuth-0.7.5.1.min.js" type="text/javascript"></script>
In order to work with the Twitter API you’ll need to set up an app in the Twitter developer centre. Head on over to dev.twitter.com to register a new app. The form is fairly simple, but the crucial field is “Application Type” which need to be set to client. For the type of client we’re writing a “Default Access type” of Read-only will suffice.

You’ll need to collect the consumer key and secret from the settings page presented after registration of your new app. They are under a heading called “OAuth 1.0a Settings”.

You’ll also need your personal access token. On the right of the settings page is a menu, you’ll need the “My Access Token” one. On that page, copy the key and the secret and you’re ready for some coding.


As a side note, you should keep all tokens private, no one else should have access to them.
With all the keys and secrets to hand, you can instantiate an OAuth object.
var oauth = OAuth({
consumerKey: "[YOUR-CONSUMER-KEY]",
consumerSecret: "[YOUR-CONSUMER-SECRET]",
accessTokenKey: "[YOUR-PERSONAL-TWITTER-ACCESS-TOKEN-KEY]",
accessTokenSecret:"[YOUR-PERSONAL-TWITTER-ACCESS-TOKEN-SECRET]"
});
We’ll start with a basic call to the Twitter API, with a simple alert. Define a success function and a failure function to handle the responses from the API as follows:
function success(data){
var timeline = JSON.parse(data.text);
timeline.forEach(function (element){
alert(element.text);
});
}
function failure(data) {
alert("Throw rotten fruit, something failed");
}
As you can see, both functions have a single argument data, to which jsOAuth will pass an object containing the response text, response headers and request headers.
Reading the Twitter API documentation, we know that a url with the extension .json will return a JSON response, so we JSON.parse() the response text held in data.text. The result is an array of tweet objects we can forEach over and alert out the status for.
Titanium has a build in JSON library, so the JSON helper is always available to us when we need to parse() or stringify() JSON data.
Finally we need to call the Twitter API end point, and pass the data to our callback functions. With jsOAuth a simple get request is as easy as:
oauth.get(URL, successCallback, failureCallback);
So plugging in our callbacks and home timeline URL we get:
oauth.get("http://api.twitter.com/1/statuses/home_timeline.json", success, failure);
Now, we need to run the code using the Titanum developer tool. Load the tool, click your project and then click the “Test & Package” tab. Here you find a button to launch and kill your app.
Go ahead click launch and your app will run, query the Twitter home timeline API finally alerting each tweet.
You’ll probably agree, that alerting out the last 20 tweets each time the application runs isn’t exactly useful. We could use a timer to call the API every few minutes. We could possibly use the since_id parameter to only get new tweets. We could also use Titanium’s notification module to get pretty notifications.
That’s all for this part of the tutorial. Next time, we’ll replace the alert with notifications, and set up a timer to collect only the latest tweets every minute.
Building a Twitter client with Appcelerator Titanium & jsOAuth - Part 2
¹ At the time of writing the current version was 0.7.5.2
Appcelerator Titanium: Bullet-Proof window drag
UPDATED: 2010-01-24
/*
Bullet Proof window drag
This is the most performant window dragging code
I could come up with. All the example on
developer.appcelerator.com we laggy
Version 2: More contained version
*/
var toolbarHandle = document.getElementById('toolbar');
toolbarHandle.addEventListener('mousedown', function (e){
var isDragging = true;
var mousePosition = {x:event.clientX, y:event.clientY};
document.addEventListener('mousemove', drag, false);
document.addEventListener('mouseup', function (e){
document.removeEventListener('mousemove', drag, false);
document.removeEventListener('mouseup', arguments.callee, false);
}, false);
function drag(event) {
var wnd = Titanium.UI.currentWindow;
var curentPosition = {x:wnd.getX(), y:wnd.getY()};
curentPosition.x += event.clientX - mousePosition.x;
curentPosition.y += event.clientY - mousePosition.y;
wnd.moveTo(curentPosition.x, curentPosition.y);
}
}, false);
You can find the code on Github
