How to use expressions in TSS

As the docs state Alloy’s TSS files use a JSON-like syntax. It’s no pure JSON, since there’s no root {} and blocks don’t need to (but can be) separated with ,.

What you can

You’re also allowed to use a limited number of special types of values, being:

  • JSON values, that is, Strings, Numbers, Objects, Array, Booleans and null
  • undefined to unset a property (do not place undefined in quotes) (since Alloy 1.4.0)
  • Titanium SDK constants, for example, Ti.UI.SIZE
  • Localization functions, either Ti.Locale.getString() and its shorthand L()
  • Variables from the Alloy.CFG or Alloy.Globals namespaces
  • Bitwise operators, which includes bit shifting (>>, <<, and >>>), bitwise AND (&), bitwise OR (|) and bitwise XOR (^) (since Alloy 1.3.0)

What you can’t

Something you can not do is using expressions like concatenating strings or calling functions for values that can change at run-time. Take this example that would give each view a random background color:

"View": {
  backgroundColor: '#' + Math.floor(Math.random()*16777215).toString(16);
}

How you can!

On my way back from Connect.js a simple workaround came to my mind for this limitation. Like we saw, you are allowed to reference variables from the Alloy.Globals namespace. And since Alloy.Globals is simply a JavaScript object you can also use Object.defineProperty() on it. With this we can make the above example work:

alloy.js

Object.defineProperty(Alloy.Globals, 'randomColor', {
  get: function() {
    return '#' + Math.floor(Math.random()*16777215).toString(16);
  }
});

index.xml

<Alloy>
  <Window>
    <View /><View /><View />
    <View /><View /><View /><View />
  </Window>
</Alloy>

index.tss

"Window": {
  backgroundColor: 'white',
  layout: 'vertical'
}

"View": {
  top: 40, width: '80%', height: 20,
  backgroundColor: Alloy.Globals.randomColor
}

The end result should be similar, but certainly not identical to:

iOS Simulator Screen Shot 20 Oct 2014 01.45.37

One more thing

The only remaining limitation is that you cannot pass a value in from TSS. So if you need to do some kind of conversion all possible values you need must be prepared in alloy.js

Code Strong!

App imagineer: Imagining, Engineering & Speaking about Native mobile Apps with Appcelerator Titanium & Alloy • Meetup organizer • Certified Expert • Titan


Comments