Custom Properties in Titanium Windows and Controls


Instantiated windows and controls in Titanium Appcelerator act like JavaScript objects. JavaScript allows you to create custom properties in objects even when that property is not defined. You can take advantage of this in Titanium to pass some information to a window that you are about to open.

For example, on a clean project, you can have this on your app.js:

/**
  * app.js
  */
var mywindow = Titanium.UI.createWindow({
  url: 'mywindow.js', // load a different window file (mywindow.js)
  backgroundColor:'#fff'
});
mywindow.username = 'John Doe'; // this will be passed to mywindow.js

mywindow.open();

Above, we are setting a custom property named username to the mywindow variable which is an instance of Titanium.UI.Window. We can now access the value of username in mywindow.js:

/**
  * mywindow.js
  */
var textfield = Ti.UI.createTextField({
  value: Ti.UI.currentWindow.username, // getting the value from app.js ("John Doe")

  borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
  height:35
});
Ti.UI.currentWindow.add(textfield);

The output would be a window with a textbox whose default value is “John Doe”. That was the value we set in app.js.

Not Just Scalar Values

You’re not limited to scalar values like what I just showed. You can also set full JavaScript objects:

// app.js
mywindow.userInfo = {
  id:  1,
  name: 'John Doe',
  location: 'Neverland'
};

And access them similarly:

// mywindow.js
alert(Ti.UI.currentWindow.userInfo.location); // "Neverland"

There is one caveat when setting objects. When setting a property to an object, you won’t be able to modify that object’s properties directly:

// app.js
mywindow.userInfo = {
  id:  1,
  name: 'John Doe',
  location: 'Neverland'
};
mywindow.userInfo.location = "Wonderland";

alert(mywindow.userInfo.location); // still "Neverland"

You’ll have to set the property again to your modified object. You can do it like this:

var userInfo = mywindow.userInfo;
userInfo.location = "Wonderland";
mywindow.userInfo = userInfo; // set the whole modified again

alert(mywindow.userInfo.location); // now "Wonderland"
alert(mywindow.userInfo.name); // other properties still work

Also applicable to controls

Remember that you can also set custom properties on controls:

var textfield = Ti.UI.createTextField({
  value: "Jane"
});

textfield.surname = "Doe";
alert(textfield.surname); // "Doe"

It comes in handy sometimes.

Final words

Watch out when setting custom properties. Make sure that the property name doesn’t exist. For this reason I prefer to set objects to a single custom property (e.g. mywindow.params).