Blog.

Mastering Ext.Direct, Part 3

Code in this post can be obsolete, however, principles and theory may still apply.

<<< Mastering Ext.Direct, Part 2

Processing responses

As I’ve already said, you cannot use the return value of an API function call as result is not know at the moment of the call return. It is never stressed enough that

Ext.Direct calls are ASYNCHRONOUS.

Therefore, all Ext.Direct created API functions, for example Example.Car.go() take one extra argument in addition to arguments you have specified in server-side class definition. That argument is callback function.

In our example, Example.Car.go() takes one argument, speed per server side method definition, however, it takes two in fact: Example.Car.go(speed, callback)

Let’s call it with a callback to test it. Type in the Firebug console:

Example.Car.go(80, console.info);

console.info is a function that prints its arguments in a human readable form. We use it as the callback so we see:

  • that it really gets called when the response arrives
  • which arguments Ext.Direct passes to the callback

As you can see, the callback is called with two arguments:

  • response – it is that what is returned by the server-side Car.go() method. It can be string (as in our example), boolean, object, array or void (nothing).
  • e – it is Ext.Direct.Event object or, being more specific, Ext.Direct.RemotingEvent.

 

The event e has some useful properties and methods, most important of them are:

  • status is true if the call was successful, false if the call failed
  • result contains same value as the first argument – it is server response data
  • type is rpc in our example but it also can be exception or others
  • action is the class name
  • method is name of the method called
  • getTransaction() is method to retrieve the transaction used in this server round trip. You would use it if you want more data on the transaction.

 

Processing exceptions

Let’s call go method again:

Example.Car.go(300, console.info);

The callback is called as before but the arguments differ:

  • response is undefined – no data from server
  • e has type exception and has property message that contains error message text

An example application

That is almost all we need to know to start using Ext.Direct in an application. I’ve written a simple one so you have something to play with.

First, create file example.js with the following content:

/**
 * Mastering Ext.Direct example script
 *
 * @author     Ing. Jozef Sakalos
 * @copyright  (c) 2009, by Ing. Jozef Sakalos
 * @date       16. September 2009
 * @version    1.0
 * @revision   $Id$
 */

Ext.BLANK_IMAGE_URL='ext/resources/images/default/s.gif';

Ext.onReady(function() {
    /**
     * This function is called when Ext.Direct request
     * response arrives from the server.
     *
     * @param {String/Object/Array/Null} response 
     * That what is returned by server method
     * @param {Ext.Direct.RemotingEvent/Ext.Direct.ExceptionEvent} e 
     */
    var callback = function(response, e) {

        // uncomment if you want to inspect arguments in Firebug Console
//        console.log(response, e);

        var status = 'Success'
        var text = '';

        // success handling - e.status is success flag: 
        // true is success, false is failure
        if(true === e.status) {
            // response argument is same as e.result
            text = response;
        }

        // failure handling
        else {
            status = 'Failure'

            // in the case of an exception, we don't have response but message
            text = e.message;
        }

        // grab the center body
        var body = win.items.itemAt(1).body;

        // display the response
        body.createChild({
             tag:'div'
            ,cls:'response'
            ,html:status + ': ' + text
        });

        // scroll down
        body.scrollTo('top', 100000, true);
    };

    // create Ext.Direct test window
    var win = new Ext.Window({
         title:'Mastering Ext.Direct by Saki'
        ,width:600
        ,height:400
        ,closable:false
        ,layout:'border'
        ,border:false
        ,items:[{
            // west region with buttons
             region:'west'
            ,width:160
            ,minSize:160
            ,split:true
            ,defaults:{minWidth:120}
            ,layout:'table'
            ,bodyStyle:'padding:20px'
            ,layoutConfig:{columns:1, tableAttrs:{style:{width:'100%'}}}
            ,items:[{
                 xtype:'button'
                ,text:'Car.start()'

                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.start.createDelegate(null, [callback])
            },{
                 xtype:'button'
                ,text:'Car.go(80)'

                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.go.createDelegate(null, [80, callback])
            },{
                 xtype:'button'
                ,text:'Car.go(250)'

                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.go.createDelegate(null, [250, callback])
            },{
                 xtype:'button'
                ,text:'Car.stop()'

                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.stop.createDelegate(null, [callback])
            },{
                 xtype:'button'
                ,text:'Send All'

                // another option is inline function that executes calls
                ,handler:function() {

                    // the following calls will be combined in one request
                    Example.Car.start(callback);
                    Example.Car.go(80, callback);
                    Example.Car.go(250, callback);
                    Example.Car.stop(callback);
                }
            }]
        },{
            // responses are displayed here
             region:'center'
            ,autoScroll:true
            ,tbar:['->', {
                text:'Clear'
               ,handler:function(){win.items.itemAt(1).body.update('')}
            }]
        }]
    });
    win.show();

});

// eof

 

Then tune your index.php so that it reads:

Mastering Ext.Direct by Saki

      .x-table-layout-cell {
        height:40px;
        text-align:center;
        vertical-align:middle;
    }
    .x-table-layout-cell table {
        margin:auto
    }
    .response {
        padding:4px 0 4px 20px;
        font-size:13px;
    }

      Ext.Direct.addProvider(Example.API);

 

Conclusion

Good! Play with Ext.Direct and let me know what you would like to have in next parts.

saki
Follow me:
Latest posts by saki (see all)

12 Responses

  1. Excelent tut, I love it. Really impressive work.
    Your tutorial shows very good how it works. One question please:
    let’s assume I like to do some request automatically all 30 seconds…How would i go to implement this…?

    Many thanks for your answer…

    Best wishes

    Michael

  2. This helped me a lot! Still need to figure out how i’m going to use it for my application though. I have a big app with authentication involved… which was a lot of trouble, and i’m not satisfied with the result, so i hope Ext.Direct will solve that.

    Btw, an authentication example with Ext.Direct would be awesome 😉

    Thanks!

  3. Great tutorial… I need to do use this with polling instead of remoting. What additional parameters etc do I need to do this?

  4. Hi Saki,
    I’m trying to make an Ext.Direct call in a class like this :

    ,generatePHP:function(grid, records, action, groupId){
    console.log(‘generatePHP’,grid,records,action,groupId);
    var table = records[0].get(‘Table’);
    CrudBd.generatePHP({Table:table}, this.handleResponse);

    }
    ,handleResponse:function(provider, response){ //,msg,title){
    console.info(‘handleResponse’,provider,response);
    }

    But it does not go into my handleResponse method … have you got an idea?
    thx a lot

  5. Great tutorial saki … thanks a lot for your work!

    The only thing that’s still missing these days is possibility to enforce a certain directory structure. I know, there’s this tutorial on how to write large apps but in the end it’s still up to the developer where he puts his stuff. Have 3 people sit on the same project and you’ll end up with inconsistencies.

    I was thinking if something along the lines of MVC frameworks like RoR or FlexMVC. If you enforce all the layers and logics to be in separate files on the framwork level there’ll be way less confusion.

    But perhaps I’m only a messy when it comes to structuring my code 🙂

  6. sorry, part of the message vanished.

    … continued with:

    As an example in Mastering Ext.Direct, 3. You gave an example with php-code car.php. Is there a way to interact direct with json files instead of php or java code?

    Do appreciate your blog including your Saki’s Ext Example Page very much. Thank you.

  7. Hello Mr. Sakalos,

    followed your series, you placed in your blog with big interest.
    Is it possible to bring json on top of interaction with the server. (To simulate json from the server json-files could be used instead.)
    As an example in

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your username and password to log into your account. Don't have an account? Sign up.

Want to collaborate on an upcoming project?