Showing posts with label Mobile. Show all posts
Showing posts with label Mobile. Show all posts

Saturday, June 30, 2012

Sencha Touch 2: Models and proxies: associations - traversing and saving

It's difficult to locate reasonable information on using a proxy with a model that has associations - it's even more difficult to actually have it work, as (in a JSON context), the standard JSON writer of Sencha Touch 2 does not traverse associations. The extended JSON writer in this post will traverse model associations and also allows one to inject handlers for any required custom formatting - else isomorphism is assumed.

Semantically, I don't personally like the relationship between a model and a proxy, it is unnatural to my mindset, but I do admit it useful on occasion. So here I present a modified example, including an extension of the standard Ext.data.writer.Json. The code presented includes hard coded url's, names and so on, which the real code base does not - as I said, and example.

First, the model, including a proxy section, with the extended writer. The User model 'hasMany' membership details - yes, not a compelling example, but it serves for illustrative purposes:

1:  Ext.define('app.model.User', {  
2:    extend: 'Ext.data.Model',  
3:    config: {  
4:        fields: [  
5:           {name: 'id',   type: 'int'},  
6:           {name: 'firstName', type: 'string'},  
7:           {name: 'surname', type: 'string'},  
8:           {name: 'age', type: 'int'}  
9:        ],  
10:        hasMany: {  
11:           model: 'app.model.MembershipDetails',  
12:           name: 'details'  
13:        },  
14:        proxy: {  
15:           type: 'ajax',  
16:           url: '/createUser',  
17:           method: 'POST',  
18:           writer: {  
19:                 type: 'associationsWriter',  
20:                 root: 'UserCreationRequest',  
21:                 encodeRequest: true  
22:           }  
23:        }  
24:     }  
25:  });  

Line 19 defines the type of the writer, which is shown below:


1:  Ext.define('app.lib.data.AssociationsWriter', {  
2:     extend: 'Ext.data.writer.Json',  
3:     alias: 'writer.associationsWriter',  
4:     config: {  
5:        // Array of objects of type:   
6:       // { name: xxx processor: function(name, data, record) { xxx },   
7:        // retain: true/false/undef}  
8:        customFieldHandlers: [],  
9:        customAssociationHandlers: []  
10:     },  
11:     constructor: function() {  
12:        this.callParent(arguments);  
13:        this.depth = -1;  
14:     },  
15:     getRecordData: function(record) {  
16:        this.depth++;  
17:        var data = this.callParent(arguments);  
18:        (this.depth == 0 ?   
19:          this.processCustomFields(data, record) : this).  
20:            processAssociations(data, record);  
21:        this.depth--;    
22:        return data;  
23:     },  
24:     processCustomFields: function(data, record) {  
25:        this.getCustomFieldHandlers().forEach(function(e) {  
26:           e.processor(e.name, data, record);  
27:           if (!e.retain) delete data[name];  
28:        }, this);  
29:        return this;  
30:     },  
31:     processAssociations: function(data, record) {  
32:        record.getAssociations().each(function(ass) {  
33:           if (ass.getType() !== 'belongsto') {  
34:              var customHandler =   
35:                this.getCustomAssociationHandlers().first(  
36:                 function(e) { return e.name === ass.getName(); }  
37:                );  
38:              var handler = customHandler ?   
39:                customHandler.processor : this.standardAssociation;  
40:              var store = ass.getStore().apply(record, null);  
41:              store.each(function (rec) {  
42:                         handler.apply(this, [ ass.getName(), data, rec ] );  
43:           }, this);  
44:           }  
45:      }, this);  
46:     },  
47:     standardAssociation: function(name, data, rec) {  
48:        if (!data[name]) data[name] = [];  
49:      data[name].push(this.getRecordData.call(this, rec));  
50:     }  
51:  });  

The key override from the base type is getRecordData(Object).The code is fairly simple, the association handling function being processAssociations. As can be seen, a standard ST2 config section in this type allows you to associate custom field and association handlers if the normal behaviour does not suit requirements.


A little clumsily, line 33 handles the case where an association is encountered that should not be traversed. An associated object (membership details) includes a 'back association' with containing object, in this instance a model type of user. 


Also noteworthy is line 40 which gets the dynamically generated store that will hold the associations objects. As can be inferred, association.getStore() returns a function, which we call using the apply function.


MembershipDetails is included below - note the FK field reference to user, 'user_id' - the default name expected by Sencha if not explicitly specified:




1:  Ext.define('app.model.MembershipDetails', {  
2:    extend: 'Ext.data.Model',  
3:    config: {  
4:        fields: [  
5:           {name: 'id',   type: 'int'},  
6:           {name: 'user_id', type: 'int'},  
7:           {name: 'joinDate', type: 'date'},  
8:           {name: 'promoCode', type: 'string'}  
9:        ],  
10:        associations: { type: 'belongsTo',   
11:                        model: 'app.model.User' }  
12:     }  
13:  });  



Finally, a different version of the model with a custom field handler and custom association handler:


1:  Ext.define('app.model.User', {  
2:    extend: 'Ext.data.Model',  
3:    config: {  
4:        fields: [  
5:           {name: 'id',   type: 'int'},  
6:           {name: 'firstName', type: 'string'},  
7:           {name: 'surname', type: 'string'},  
8:           {name: 'age', type: 'int'}  
9:        ],  
10:        hasMany: {  
11:           model: 'app.model.MembershipDetails',  
12:           name: 'details'  
13:        },  
14:        proxy: {  
15:           type: 'ajax',  
16:           url: '/createUser',  
17:           method: 'POST',  
18:           writer: {  
19:                 type: 'associationsWriter',  
20:                 root: 'UserCreationRequest',  
21:                 encodeRequest: true,  
22:                 // Custom handler only required when there is not an   
23:                 // isomorphic relationship between the model and target  
24:                 customFieldHandlers: [  
25:                    { name: 'surname', processor: function(name, data, record) {  
26:                                      data['lastName'] = record.get(name);  
27:                                    }  
28:                    }  
29:                 ],  
30:                 customAssociationHandlers: [  
31:                    // Name here matches the name of the association defined above  
32:                    { name: 'details', processor: function(name, data, record) {  
33:                          data[key] = {  
34:                                'when' : record.get('joinDate'),  
35:                                'voucher' : record.get('promoCode')     
36:                             };  
37:                          }  
38:                    }  
39:                 ],  
40:              }  
41:      }  
42:     }  
43:  });  

Line 25 has a field handler that morphs the surname property, making it instead lastName in the generated JSON request. Line 32, takes the details association and changes the names of the joinDate and promoCode - of course, more sophisticated actions are possible. The default behaviour in the extended writer is to not further process or include in the generated request any fields or associations that are handled by custom handlers - but this can be overridden by including a 'retain: true' association  in the custom handler definition.

Saturday, December 3, 2011

Sencha Touch: Repeating tasks

And so, some trivia, dear reader (I tried to discover the etymology of 'dear reader' - and drew a blank). You may use Ext.defer on occasion, and perhaps even the DelayedTask class. But you need to fall back to 'raw' Javascript to create repeating tasks; so here is a trivial set of extensions to the Ext.util.Functions class that provide the ability to create repeating tasks, and some simple management of them. This use of base behaviour is not uncommon - how do you clear local storage? window.localstorage.clear().

 Ext.apply(Ext.util.Functions, {  
    repeat: function(taskName, fn, millis, zeroDayExecution) {
       this.tasks = this.tasks || {};  
       if (zeroDayExecution)  
          fn();  
       return this.tasks[taskName] = window.setInterval(fn, millis);  
   },  
   cancelRepeatingTask: function(taskName) {  
    if (this.tasks) {
      var id = this.tasks[taskName];  
      if (!Ext.isEmpty(id)) {  
         window.clearInterval(id);  
         delete this.tasks[taskName];  
      }
    }
   },  
   cancelAllRepeatingTasks: function() {  
    if (this.tasks)  
       Object.keys(this.tasks).forEach(function(key) { 
                                       this.cancelRepeatingTask(key); }, 
                                       this);         
   }  
 });  

Tuesday, November 15, 2011

Sencha Touch: Workflow framework published


I've been working on a workflow framework for Sencha Touch, after repeatedly being in the position of wanting to compose tasks in an intelligible, maintainable and flexible manner. It employs some simple OO abstractions, a nod towards separation of concerns, and the handy inbuilt event framework of Sencha. It also utilises JSinq, which I find a rather handy little library - although it is relatively easy to convert to not use it in case of concerns over download/package size.
The project is published on codeplex: http://mobileflow.codeplex.com/
Project overview (excerpt)
A workflow framework for Sencha Touch mobile apps including automatic component management. The intent is to start 'small', with a basic workflow engine, and build to include hydration/dehydration of workflow instances (using the memento pattern and local storage for example) and a visual designer and DSL style code generation.
Currently uses Sencha Touch 1.1, but will upgrade to 2.0 when out of the preview stage.

Sunday, October 23, 2011

Sencha Touch: Ext.Picker.Slot and the disappearing template

Ext.Picker is a useful component indeed. But recently, one aspect of an associated class's implementation made me wonder exactly why it was done in such a way. Specifically, the class implementation mounted an effective defense against using custom templates as the slot rendering mechanism, so I couldn't include images in the slot at all - which is exactly what I needed to do. Note that the behaviour inherited from DataView implies you can just supply a 'tpl' in configuration - but that just is not true.

(Note that the names of types and so on used in this post have been modified from the original implementation).

The class of interest is Ext.Picker.Slot, a private class and the default one for Ext.Picker 'slots'. Inside initComponent(), this assignment was the issue - forcing a standard template on you whether you like it or not:

 this.tpl = new Ext.XTemplate([  
       '<tpl for=".">',  
         '<div class="x-picker-item {cls} <tpl if="extra">x-picker-invalid</tpl>">{'   
          + this.displayField + '}</div>',  
          '</tpl>'  
     ]);  

There are a few ways of forcing the template you want in, but I chose to extend Ext.Picker.Slot, invoke the super type constructor, and then apply the template. As Sencha stress, Ext.Picker.Slot is a private class, so this can be regarded as a temporary measure, and not guaranteed to work with ST 2.0.

 m.ui.CustomSlot = Ext.extend(Ext.Picker.Slot, {  
   constructor: function(config) {  
     m.ui.CustomSlot.superclass.constructor.apply(this, arguments);  
     if (!Ext.isEmpty(config.template))   
        this.tpl = config.template;  
    }  
 });  
 Ext.reg('customslot', m.ui.CustomSlot);  

As part of the definition process, the type is 'xtype' registered with Sencha. Below is an example of the template I need to apply:

 m.ui.pickerSourceObjectTpl = new Ext.XTemplate(  
 '<tpl for=".">',  
 '<div class="x-picker-item {cls} <tpl if="extra">x-picker-invalid</tpl>">',  
 '<div class="m-item-image">{[this.getImageElement(values)]}</div>',  
 '<div class="m-item-info">',  
 '<p class="m-name header">{[this.getDisplayName(values)]}</p>',  
 '</div>',   
 '</div>',   
 '</tpl>',  
 {  
   getImageElement: function(obj) {  
    return m.ui.renderingSupport.getImageHTMLElement(obj);  
   },  
   getDisplayName: function(obj) {  
    return !Ext.isEmpty(obj.CustomisedName) ?   
        obj.CustomisedName : obj.Name;  
   }  
 });  

As I have some very specific behaviour associated with the picker implementation, I extended Ext.Picker. Note that there is a custom css class associated with the picker (class 'm-picker') - this is important for the actual operation of the picker in 'proper template' mode, as we need to set the attributes of the picker bar properly, or it looks rather strange.

1:  m.sencha.views.CustomPicker = Ext.extend(Ext.Picker, {  
2:    cls: 'm-picker',  
3:    defaultType: 'customslot',  
4:    constructor: function(config) {  
5:      m.sencha.views.CustomPicker.superclass.constructor.apply(this, arguments);  
6:      this.currentSource = '';  
7:      this.currentTarget = '';  
8:    },  
9:    filter: function() {  
10:      m.sencha.stores.sources.filterBy(function(rec, id) {  
11:        return m.domain.currentSession.isValidSource(rec.get('Number'));  
12:      });  
13:      this.slots[0].setSelectedNode(0);  
14:    },  
15:    listeners: {  
16:      pick: function(picker, obj, slot) {  
17:        this.currentSource = this.dispatchChangeToController({  
18:           action: 'sourceChanged',  
19:           selection: obj.Source,  
20:           cached: this.currentSource  
21:        });  
22:        this.currentTarget = this.dispatchChangeToController({  
23:           action: 'targetChanged',  
24:           selection: obj.Target,  
25:           cached: this.currentTarget  
26:        });  
27:      }  
28:    },  
29:    dispatchChangeToController: function(options) {  
30:     if (options.cached != options.selection && !Ext.isEmpty(options.selection)) {  
31:          Ext.dispatch({  
32:            controller: m.sencha.controllers.activeDispositionController,  
33:            action: options.action,  
34:            number: options.selection,  
35:            context: !Ext.isDefined(this.context) ? 'self' : this.context  
36:          });  
37:       }    
38:       return options.selection;  
39:    }  
40:  });  

Part of the SASS defintion for the custom css class is shown below - note that I am in no way a SASS or css expert, and I can claim no responsibility for what is excerpted below:

 .x-sheet.m-picker{  
      top:0 !important;  
      height:$picker-row-height*2 !important;  
      .x-picker-mask{  
          .x-picker-bar{  
              background:none;  
              border-top:rgba(0,0,0,0.2) 1px solid;  
              border-bottom:rgba(0,0,0,0.2) 1px solid;  
              @include box-shadow(rgba(0,0,0,0.1) 0 0 4px 0);  
          }  
      }  

Finally, we create slots to place in the picker sub type, at another place in code. Here, we just use the registered xtype, supply some base slot properties, and use the custom template property to specify our desired template.

1:  var slots = [{  
2:        xtype: 'customslot',  
3:        name: 'Source',  
4:        store: m.sencha.stores.sources,  
5:        valueField: 'Number',  
6:        template: m.ui.pickerSourceObjectTpl,  
7:        displayField: 'Name'  
8:      },  
9:      {  
10:        xtype: 'customslot',  
11:        name: 'Target',  
12:        store: m.sencha.stores.targets,  
13:        valueField: 'Number',  
14:        template: m.ui.pickerTargetObjectTpl,  
15:        displayField: 'Name'  
16:      }];  

Saturday, October 15, 2011

Dynamically building and destroying Sencha Touch components

This item targets Sencha Touch 1.1 - with Sencha Touch 2.0 on the horizon, it will be interesting to see if any of this might be better addressed.

Following some of the advice on optimising a Sencha Touch application, I decided it would be useful to build components on demand and handle their lifecycle in a centralized fashion. Further, encapsulate this behaviour in a controller base type, and retain references to dynamically constructed components statically, so all controller sub types can deal with components consistently. (As should be apparent, this example code is culled from an MVC implementation).

The implementation in its entirety follows, then a brief segmented explanation of the salient points.

1:  m.sencha.controllers.BaseController = Ext.extend(Ext.Controller, {  
2:    /*  
3:     * options.viewportProperty, options.buildFunction, options.name,   
4:     * options.callback, options.maskText  
5:    */  
6:    buildOnDemand: function(options) {  
7:      var requiresBuild = !Ext.isDefined(options.viewportProperty) ||   
8:                options.viewportProperty.isDestroyed;  
9:      if (!requiresBuild) {  
10:        this.activateBuiltComponent(options);  
11:      }  
12:      else {  
13:        var enclosingController = this;  
14:        m.ui.platformFactory.showMask(  
15:           Ext.isDefined(options.maskText) ? options.maskText : 'Loading...',  
16:           function(mask) {  
17:              var compConfig = options.buildFunction();  
18:              options.viewportProperty = compConfig[options.name];  
19:              m.sencha.views.viewport.applyAndAdd(compConfig, options.name);  
20:              mask.hide();  
21:              m.sencha.controllers.BaseController.  
22:                demandBuiltComponents[options.name] = compConfig[options.name];  
23:              enclosingController.activateBuiltComponent(options);  
24:        },  
25:        m.config.shortMaskDelay  
26:       );  
27:      }  
28:    },  
29:    activateBuiltComponent: function(options) {  
30:      m.sencha.views.viewport.setActiveItem(options.viewportProperty);  
31:      if (options.callback)   
32:        options.callback(options.viewportProperty);  
33:    },  
34:    cleanup: function() {  
35:     for(var compName in m.sencha.controllers.BaseController.demandBuiltComponents)   
36:        this.destroyAsNecessary(compName);  
37:    },  
38:    destroyAsNecessary: function(name) {  
39:     var target =   
40:       m.sencha.controllers.BaseController.demandBuiltComponents[name];  
41:     if (Ext.isDefined(target) &&   
42:       (!Ext.isFunction(target.isDestroyed) || !target.isDestroyed))   
43:        m.sencha.views.viewport.remove(target, true);  
44:     m.sencha.controllers.BaseController.demandBuiltComponents[name] = null;    
45:    },  
46:    constructor: function() {  
47:      m.sencha.controllers.BaseController.superclass.constructor.apply(this, arguments);    
48:    }  
49:  }); 
50:  m.sencha.controllers.BaseController.demandBuiltComponents = {};  

To  the important aspects of the implementation:

1:  m.sencha.controllers.BaseController = Ext.extend(Ext.Controller, {  
2:    /*  
3:     * options.viewportProperty, options.buildFunction, options.name,   
4:     * options.callback, options.maskText  
5:    */  
6:    buildOnDemand: function(options) {  
7:      var requiresBuild = !Ext.isDefined(options.viewportProperty) ||   
8:                options.viewportProperty.isDestroyed;  
9:      if (!requiresBuild) {  
10:        this.activateBuiltComponent(options);  
11:      }  
12:      else {  
13:        var enclosingController = this;  
14:        m.ui.platformFactory.showMask(  
15:           Ext.isDefined(options.maskText) ? options.maskText : 'Loading...',  
16:           function(mask) {  
17:              var compConfig = options.buildFunction();  
18:              options.viewportProperty = compConfig[options.name];  
19:              m.sencha.views.viewport.applyAndAdd(compConfig, options.name);  
20:              mask.hide();  
21:              m.sencha.controllers.BaseController.  
22:                demandBuiltComponents[options.name] = compConfig[options.name];  
23:              enclosingController.activateBuiltComponent(options);  
24:        },  
25:        m.config.shortMaskDelay  
26:       );  
27:      }  
28:    },    

  • Line 6 declares the build function, intended to be used by clients to request an object is constructed and managed by the controller statically. An 'options' object is expected, with the options as noted in the comment.
  • Lines 7-9: If the component exists and is not marked as destroyed,  just activate it
  • Lines 13-25: Create a 'closure' style reference to the executing controller, and invoke an Ext deferred task to show a mask while the component is built (this is performed using a local 'platform' object). A deferred task is used as failing to 'yield' for a short period of time may cause the loading mask to not show at all.
  • Lines 17-20: Execute the client supplied build function to create a new instance of the desired component, and have the view port (a panel with a card layout) add the component to itself. Hide the mask.
  • Lines 21-22: Record the component in a static object shared by all controller sub types
  • Line 23: Activate the component 
 
29:    activateBuiltComponent: function(options) {  
30:      m.sencha.views.viewport.setActiveItem(options.viewportProperty);  
31:      if (options.callback)   
32:        options.callback(options.viewportProperty);  
33:    },    
  • Line 30: Have the view port activate the just built or pre-existing component
  • Lines 31-32: If the options supplied include a callback function to be executed after component activation, call it now
Now some general cleanup and management behaviour. Line 34 (following) declares a sweeping cleanup function, line 38 a function to destroy a named component. Note that we examine the object to see if the isDestroyed property is defined by the component instance - this property is dynamic, in that it does not exist for a component unless it has been destroyed.

34:    cleanup: function() {  
35:     for(var compName in m.sencha.controllers.BaseController.demandBuiltComponents)   
36:        this.destroyAsNecessary(compName);  
37:    },  
38:    destroyAsNecessary: function(name) {  
39:     var target =   
40:       m.sencha.controllers.BaseController.demandBuiltComponents[name];  
41:     if (Ext.isDefined(target) &&   
42:       (!Ext.isFunction(target.isDestroyed) || !target.isDestroyed))   
43:        m.sencha.views.viewport.remove(target, true);  
44:     m.sencha.controllers.BaseController.demandBuiltComponents[name] = null;    
45:    },  
46:    constructor: function() {  
47:      m.sencha.controllers.BaseController.superclass.constructor.apply(this, arguments);    
48:    }  
49:  }); 
50:  m.sencha.controllers.BaseController.demandBuiltComponents = {};  

Moderately tidy and (ironically enough) in need of some optimisation itself.

Saturday, July 30, 2011

Sencha Touch: Using abstraction to handle platform differences

Sencha Touch does an excellent job of abstracting platform differences in the main. One thing I don't like though, is the style they seem to espouse for handling platform differences in application code. For example, this is from  the source of the Kitchen Sink demo:

1:  demos.List = new Ext.TabPanel ({  
2:    items: [{  
3:      title: 'Simple',  
4:      layout: Ext.is.Phone ? 'fit' : {  
5:        type: 'vbox',  
6:        align: 'center',  
7:        pack: 'center'  
8:      },  

What is line 4 doing? Expressing a platform 'exception' using a ternary operator. I don't like that, and if the differences ever eventuate for more than two options; well, it becomes ugly and clumsy very quickly.

So I implemented a simple 'abstract class' driven implementation. I have an example currently that I'm catering for - hooking up a physical back button event handler. For iOS, this does not mean anything, but it does for Android.

So I have a base type that offers a small interface, redacted here, (but which will be extended over time) that platform specific types can extend. It subtypes the Ext.util.Observable type, as events are suspected to be required at some stage. Note that namespace root of "x" is not the real world token.

1:  x.mobile.ui.platformBase = Ext.extend(Ext.util.Observable, {  
2:    constructor: function(config) {  
3:      this.name = config.name;  
4:      x.mobile.ui.platformBase.superclass.constructor.call(this, config);  
5:    },  
6:    deviceZone: function() {  
7:      return "smartphone";  
8:    },  
9:    unexpectedError: function(msg) {  
10:      Ext.Msg.alert('Sorry!', 'Failed to ' + msg, Ext.emptyFn);  
11:    },  
12:    onDeviceBoot: function() {}  
13:  });  

The method of interest is located at line 12. I want to be able to call that and have the current implementation (whatever that might be) execute the correct behaviour - for iOS a NOP (default implementation) and for Android, using PhoneGap to override back button behaviour - which without interference, will exit the application no matter where you are in terms of navigation - which is not classed as friendly!

The Android implementation appears next. Create a namespace for Android support, and override the onDeviceBoot function to to direct the back button event (PhoneGap 0.9.5.1) to a defined handler function.

1:  Ext.namespace('x.mobile.ui.android');  
2:  x.mobile.ui.android.platform = Ext.extend(x.mobile.ui.platformBase, {  
3:    constructor: function(config) {  
4:      x.mobile.ui.android.platform.superclass.constructor.call(this, config);  
5:    },  
6:    onDeviceBoot: function() {  
7:      document.addEventListener("backbutton",  
8:                                x.mobile.ui.android.androidBackKeyHandler, true);  
9:    }  
10:  });  
11:  x.mobile.ui.android.androidBackKeyHandler = function() {  
12:    console.log('Back key usage detected');  
13:    x.mobile.ui.eventHistory.back();  
14:  };  

Lines 11-13 handle the back button depression; line 13 calls an internal implementation of a history stack, which moves to the previous location.

And this is the index.html inline script that informs the current platform 'helper' that we are in device boot mode:

1:  <script charset="utf-8" type="text/javascript">  
2:        document.addEventListener("deviceready", boot, false);  
3:        function boot() {   
4:            x.mobile.ui.platform.onDeviceBoot();  
5:            x.mobile.sencha.launch();  
6:        };  
7:  </script>  

Line 4 calls the relevant function on the x.mobile.ui.platform object, which is set to an instance of a sub type of platformBase, created by internal machinery by a trivial factory.

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.

Saturday, June 18, 2011

Sencha Touch and WCF sourced JSON handling

I've been experimenting recently with Sencha Touch; ostensibly looking at it in the cross platform mobile development space (when used in conjunction with PhoneGap). It's really rather nice - a sprawling OO edifice that will take some time to 'climb'. It embraces a classical OO way of doing things - in an amusingly (or appealingly for a classicist like myself) orthogonal manner to Javascripts prototype based system.

Anyway, I wrote some RESTful WCF services that serve up various JSON responses, and in this particular case, the standard markup of WCF gave me a minor headache for a short while, before the rather obvious solution became apparent. The part of the app discussed here relates to retrieving a list of accounts, for later display in a DataView (List).

Below is a sample of the JSON as received - a wrapper (Accounts), some information about the success of the call (kept simple for reasons of information disclosure and security), and finally a collection of account 'objects', in the Accounts array.

 {"Accounts":  
  {"Success":true,"Authenticated":true,  
  "Accounts":[  
   {"DisplayableNumber":"99-9110-0780838-00",  
   "Name":"CL33330",  
   "Number":"999110078083800",  
   "AvailableFunds":6002255,  
   "Balance":2255,  
   "CustomisedName":null,  
   "Type":"Revolving Home Loan"},  
   {"DisplayableNumber":"99-9110-1351434-01",  
   "Name":"J S M CL33328, T CL33329",  
   "Number":"999110135143401",  
   "AvailableFunds":165414,  
   "Balance":-34586,  
   "CustomisedName":null,  
   "Type":"Now"},  

Being only trivially skilled with Sencha Touch, I elected to follow a 'text book' approach, defining a model and associated store. The model is where the interesting part lies:
  • Lines 2-9: Define a simple namespaced account object, using the properties defined in the JSON response
  • Lines 10-16: Define an AJAX proxy for the model. The URL looks strange because this being tested with Eclipse/ADT/Android 2.2, but the RESTful nature of it should be apparent. We configure an inbuilt JSON reader, with the root of Accounts.Accounts. This is the part that befuddled me for a few minutes - there was no example of a compound root to be found; plenty of other examples, but not that. Anyway, this is the key to successful parsing of the response we have.
1:  consumerapp.models.Account =   
2:  Ext.regModel("consumerapp.models.Account", {  
3:    fields: [  
4:      {name: "Name", type: "string"},  
5:      {name: "CustomisedName", type: "string"},  
6:      {name: "Number", type: "string"},  
7:      {name: "DisplayableNumber", type: "string"},  
8:      {name: "Balance", type: "int"}  
9:    ],  
10:    proxy: {  
11:      type: 'ajax',  
12:      url : 'https://10.0.2.2:8000/SecuredServices.svc/Accounts',  
13:      reader: {  
14:        type: 'json',  
15:        root: 'Accounts.Accounts',  
16:      }  
17:    }  
18:  });  

And finally, we associate the model with a custom store, which still has some debug code in it :-)

 consumerapp.stores.accounts = new Ext.data.Store({  
   model: "consumerapp.models.Account",  
   sorters: 'Name',  
   getGroupString : function(record) {  
     return record.get('Name')[0];  
   },  
   listeners: {  
   beforeload: function (store, operation) {    
     console.log('Before loading the store');  
   }  
   },   
 });