Ext.Direct with Sencha Touch 2 with Node.JS and Express.JS

In the last post, I simply set up a very basic structure for a Sencha Touch 2 application using node.js and express.js to deliver the application. Pretty dull stuff right! I thought it would be interesting to wire up the node Ext.Direct npm module into this test Sencha Touch 2 application.

First step is to install the module itself which is straightforward:

[whit@:~/node/sencha_touch_direct] $ npm install extdirect
...

The docs on the npm module suggest adding some code to the Sencha Touch application. Here is the snippet I added just above the application:

...

Ext.require([
    'Ext.direct.*'
]);

Ext.onReady(function(){
    Ext.direct.Manager.addProvider(ExtRemote.REMOTING_API);
});

Ext.application({
...

This makes sense, we’re requiring the Ext.direct libraries and making our reference to the remote API which we will specify shortly. Next we’re going to make a call from the index.html file to call that api from the url which is /directapi

/index.html

<!-- The line below must be kept intact for Sencha Command to build your application -->
    <script id="microloader" type="text/javascript" src="touch/microloader/development.js"></script>
    <script type="text/javascript" src="/directapi"></script>

In this test app, I created a folder called direct and added the api object containing the object and functions I want to make available to the client. To start of simply I’m just going to expand on an older example I found from IBM which simply allows for connecting and calling the remote functions via Ext.direct. Here is my simple api for this test application.

/direct/DXServerDate.js

var DXServerDate  = {
    now: function(callback){
        callback(new Date());
    }
}

module.exports = DXServerDate;

Next I created a configuration json file for the extdirect module and wired everything up.

/config.json

{
    "EXTDIRECT_NAMESPACE" : "ExtRemote",
    "EXTDIRECT_API_NAME" : "REMOTING_API",
    "EXTDIRECT_PATH" : "/direct",
    "EXTDIRECT_PREFIX" : "DX"
}

Note

I was wondering what the purpose of the prefix “EXTDIRECT_PREFIX” : “DX” was in the configuration. The module author, Juris Vecvanags responded immediately explaining:

For example you might want 2 different sets, one DX, other ADMIN. This way api generator will know what to include in generated api response.

This makes sense – I can see scenarios where you may have several clients connecting with different requirements for functionality which is available to them so this works. In this example, I’m going to just use the default configuration that is provided in the extdirect module example. So my DXServerDate has the prefix DX.

Ok enough of that! Now… finally lets route the /directapi in Express to point to our API. First we add our references to extdirect and a new library nconf(to read the config.json file. You will need to npm install nconf to add this module)


var  nconf = require('nconf'),
     extdirect = require('extdirect');

nconf.env().file({ file: 'config.json'});

// read in the config.json configuration
var EXTDIRECT_PATH = nconf.get("EXTDIRECT_PATH"),
    EXTDIRECT_NAMESPACE = nconf.get("EXTDIRECT_NAMESPACE"),
    EXTDIRECT_API_NAME = nconf.get("EXTDIRECT_API_NAME"),
    EXTDIRECT_PREFIX = nconf.get("EXTDIRECT_PREFIX");
...
...
// handle the request for the api from the client
app.get('/directapi', function(request, response) {
    var api = extdirect.getAPI(EXTDIRECT_NAMESPACE, EXTDIRECT_API_NAME, EXTDIRECT_PATH, EXTDIRECT_PREFIX);
    response.writeHead(200, {'Content-Type': 'application/json'});
    response.end(api);
});

app.get(EXTDIRECT_PATH, function(request, response) {
    response.writeHead(200, {'Content-Type': 'application/json'});
    response.end(JSON.stringify({success:false, msg:'Unsupported method. Use POST instead.'}));
});

app.post(EXTDIRECT_PATH, function(request, response) {
    extdirect.processRoute(request, response, EXTDIRECT_PATH);
});

Now everything is more or less wired up. Now for this example, I’m going to make a call to the remote object, call the now() function and pass the server’s date to the Sencha Touch app’s main page! This all happens in the launch function of the app.js file. Here’s the code:

/public/touch_workspace/touchApp/app.js

...
...
 launch: function() {
        // Destroy the #appLoadingIndicator element
        Ext.fly('appLoadingIndicator').destroy();
        // lets get the date from the Direct service and then set the html!
        ExtRemote.DXServerDate.now(function(res) {

            var mainForm = Ext.create('TouchApp.view.Main');         
            console.log('The Server Date is ' + res);
            // Initialize the main view
            Ext.Viewport.add(mainForm);
            // set the html to the date!
            mainForm.setServerDate(res);

        });

    },
...
...

Here is the Main.js file. I’ve added an id called mainpage to the first tab and use Ext.getCmp to retrieve it in the setServerDate function. I know this is bad form, but I’ll be addressing this in a future post.

/public/touch_workspace/touchApp/app/view/Main.js

Ext.define('TouchApp.view.Main', {
    extend: 'Ext.tab.Panel',
    xtype: 'main',
    requires: [
        'Ext.TitleBar',
        'Ext.Video'
    ],
    config: {
        tabBarPosition: 'bottom',
        items: [
            {
                title: 'Welcome',
                iconCls: 'home',
                id: 'mainpage',
                styleHtmlContent: true,
                scrollable: true,

                items: {
                    docked: 'top',
                    xtype: 'titlebar',
                    title: 'Welcome to Sencha Touch 2'
                },

                html: [
                    "The date on the server is not set"
                ]
            },
            {
                title: 'Get Started',
                iconCls: 'action',

                items: [
                    {
                        docked: 'top',
                        xtype: 'titlebar',
                        title: 'Getting Started'
                    },
                    {
                        xtype: 'video',
                        url: 'http://av.vimeo.com/64284/137/87347327.mp4?token=1330978144_f9b698fea38cd408d52a2393240c896c',
                        posterUrl: 'http://b.vimeocdn.com/ts/261/062/261062119_640.jpg'
                    }
                ]
            }
        ]
    },
    setServerDate: function(adate){
        var panel = Ext.getCmp('mainpage');
        console.log(panel);
        panel.setHtml('The date on the server is: ' + adate);
    }
});

Do a $node app.js from the terminal and voila! – here is the app running showing our Server’s date and time:

Conclusion

Its pretty easy to wire up a Sencha Touch 2 app with Ext.Direct using node.js and express.js by using the npm module extdirect. This opens up your mobile application development to a powerful, scalable technology stack where the possibilities are endless!

Available to help your team or project:

As always, if you need help with your project, feel free to contact me.

We currently have resources available to help your project using a wide variety of server side technologies including PHP, Ruby on Rails, Java EE, .NET and node.js. Contact us and see how we can help increase your development velocity!

Looking forward to hearing from you!

Contact

Connect with me on LinkedIn

our Direct Contact Info
and finally our Sencha Devs profile

Source

The source for this example is available if you are having some trouble following along. Connect with me or send me a note and I’ll send you the source.

Resources

extdirect npm module
IBM Ext.Direct article

Google+