Saturday, June 25, 2011

Sencha Touch: Custom Ext.XTemplates

Sencha Touch is seriously tasty! My proof of concept app has moved on in leaps and bounds now that I've started to get a 'feel' for how a ST app should be structured, the best way to distribute intelligence and responsibilities amongst objects and using the documentation and source browsing to proper effect. It is really quite refreshing to write a Javascript based client in an MVC manner.

Anyway, this is a simple 'trick' for customising XTemplates. My situation: I need to apply a particular css class (or not) when the item being bound to the template meets certain conditions - in this case, when a numeric field is negative. Here is the full template (remember, POC code, so not how it would be finally):

1:  new Ext.XTemplate(  
2:    '<tpl for=".">',  
3:      '{Name}<br/>Balance:',  
4:          '<span class="{[this.getBalanceClass(values.Balance, xindex)]}">',  
5:          '{Balance}</span><br/>{Number}',  
6:    '</tpl>',  
7:    '<div class="x-clear"></div>',  {  
8:    getBalanceClass: function(balance, index) {  
9:      return balance < 0 ? "negative" : "";  
10:    }  
11:   }  
12:  );  

Points:

  • Line 4: Call a custom function(getBalanceClass) with the items 'Balance' property (which is defined in the model as a numeric)
  • Lines 8-10: Define getBalanceClass; return the css class name of "negative" if balance is, well, negative, otherwise, just an empty string 

Appealing in its simplicity.

No comments: