API Development

How to Chain Controller Methods in Titanium by Using Alloy

Alloy Tech Tip

A nice feature of Titanium and Alloy is the ability to create controllers and be reactive to triggers OR call methods without creating a pointer.

So, let’s assume that we want to open a modal settings view and react to the settings being saved BEFORE closing the view. In this case, we might typically write:

var settings = Alloy.createController(“screens/settings”);
settings.getView().open({modal:true});
settings.on("saved", function(){
  // do stuff here
  settings = null;  
});

This approach is fine, but it’s a lot of code.

With Alloy, you can chain methods and do ALL this without ever creating the pointer variable:

Alloy.createController(“screens/settings”).on("saved", function(){
  // do stuff here
}).getView().open({modal: true});

So, basically, we’ve achieved the same thing in a few lines of code — no pointer created, no potential memory leak issues!

Enjoy!