[to] ExtJS 4.2 tutorial -07:Ext.Direct

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Reprinted from the off network, the original address:

In the last section, we introduce the server data agent in ExtJS, in the introduction to the Direct proxy, we mentioned Ext.Direct. In this section we will focus on Ext.Direct specific usage, and the Direct section in the agency added.

Ext.Direct provides a mechanism for using Javascript to call the server method, it has nothing to do with the server technique, so it can be in the PHP, Java, using the technique of.Net and many other platforms.

In this section, we take RemotingProvider as an example to explain the. For the RemotingProvider implementation process, is roughly: the definition of API, and add API to Ext.direct.Manager, and then we will by calling the API to perform remote requests. Request process, ExtJS will create an Ajax request, the Remoting related data is sent to the server's Remoter page, Remoter will split the, according to action (corresponding to the class name), method (corresponding to the method name) different method calls, completed execution after the call, will return good results to the client.

API and Router

When using Ext.Direct, we need the background, methods are encapsulated into API form, and then registered in Ext.direct.Manager.

Typically, API can be configured according to the Xiang Shengcheng program, called the generation, it is according to the configuration items to generate executable code in Javascript, and with <script> tag form into the page. We will use the direct definition of this way to complete the. The following code:

var userAPI = Ext.create('Ext.direct.RemotingProvider', {
    url: rootUrl + 'DirectAPI/Router',
    actions: {
        User: [
            {
                name: 'GetUserList',
                len: 0
            },
            {
                name: 'GetUser',
                params: ['name']
            }
        ]
    }
});

UserAPI provides two operations, respectively is GetUserList and GetUser, they all data class User. URL pointed to DirectAPI/Router, we need to add a DirectAPIController in the program, and then three methods defined inside, the code as follows:

public class DirectAPIController : Controller
{
    public static List<User> UserList = null;

    static DirectAPIController()
    {
        if (UserList == null)
        {
            UserList = new List<User>();
            UserList.Add(new User() { name = "www.qeefee.com", age = 1 });
            UserList.Add(new User() { name = "QF", age = 26 });
        }
    }

    //
    // GET: /DirectAPI/
    [HttpPost]
    public JsonResult Router(FormCollection collection)
    {
        Stream input = Request.InputStream;
        input.Seek(0, SeekOrigin.Begin);

        byte[] buffer = new byte[input.Length];

        Request.InputStream.Read(buffer, 0, (int)input.Length);
        string inputString = Encoding.UTF8.GetString(buffer);
        dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(inputString);

        ExtResult result = new ExtResult();
        result.tid = json.tid;
        result.action = json.action;
        result.method = json.method;
        result.type = json.type;

        string method = json.method;
        switch (method)
        {
            case "GetUserList":
                {
                    result.result = GetUserList();
                }
                break;
            case "GetUser":
                {
                    string name = json.data.name;
                    result.result = GetUser(name);
                }
                break;
        }
        return Json(result);
    }

    public List<User> GetUserList()
    {
        return UserList;
    }

    public User GetUser(string name)
    {
        return UserList.Find(m => m.name == name);
    }

}

The code is a bit long feel shy! The main code in the Router method, when reading data, I use Request can not obtain, but under can only read InputStream, know why cannot read Request friends also hope to inform.

In the method the POST client data transfer is read, and then converted to the Json string. The conversion is completed according to method routing, transfer the results to the client.

Here are the encapsulation of the returned data, ExtResult code is as follows:

public class ExtResult
{
    public string action { get; set; }
    public string method { get; set; }
    public int tid { get; set; }
    public string type { get; set; }
    public object result { get; set; }
}

The client calls

We have previously defined API, we can easily define good method:

User.GetUserList(function (result, event, success, options) {
    var msg = [];
    Ext.Array.each(result, function (item) {
        msg.push(item.name + "  " + item.age);
    });
    Ext.MessageBox.alert('Prompt', msg.join('<br />'));
});

We have previously defined User as a static class, GetUserList is a static method of it, we can call back methods like C#.

In addition to the direct call, we can combine the DirectProxy introduced in the last lesson to use:

//Create Store
var store = Ext.create('Ext.data.Store', {
    model: 'Person',
    proxy: {
        type: 'direct',
        directFn: User.GetUserList,
        reader: {
            type: 'json'
        }
    }
});

//Loading store
store.load({
    callback: function (records, operation, success) {
        var msg = [];
        store.each(function (item) {
            msg.push(item.get('name') + '   ' + item.get('age'));
        });
        Ext.MessageBox.alert('Prompt', msg.join('<br />'));
    }
});

Parameter transfer

Ext.Direct supports two types of parameter passing mode: anonymous and named parameters.

Anonymous parameters is supported in Ext.Direct after the launch, it does not specify a parameter name, specify only the number of parameters, at the time of the call will parameter as a string array passed to the background. For example, we added GetUserByName a method for User, which takes a name parameter, we use anonymous parameter form:

{
    name: 'GetUserByName',
    len: 1
}

At the time of the call, the parameters in the callback method before writing:

User.GetUserByName('QF', callback);

If the use of anonymous parameters, then how many parameters to write the number of parameters in the callback before, finally these parameters passed as part of the data to the server.

image

Named parameter is added in Ext 4.2, it allows the name specified in the definition of parameters, and then use the JSON at the time of the call format transfer parameters, the GetUser method we previously defined for example, it has a name parameter:

{
    name: 'GetUser',
    params: ['name']
}

At the time of the call, we need to use the JSON format data, corresponding to specify a parameter name value:

User.GetUser({ name: 'QF' }, callback);

As time passed to server data form:

image

News subscription

Ext.Direct provides news subscription mechanism convenient for us. If we want to subscribe to the name "message" message, you can use the following code completion:

Ext.direct.Manager.on('message', function (e) {
    Ext.MessageBox.alert('Prompt', e.result);
});

At this point, if the data returned from the server, type event, name message, will pop-up prompts. Data returned by server:

image

 

Polling - PollingProvider

Ext.Direct also provides a polling request, it will repeat the operation of the database in the specified period of time.

var polling = Ext.create('Ext.direct.PollingProvider', {
    url: rootUrl + 'DirectAPI/GetMessage',
    type: 'polling',
    interval: 5000,
    listeners: {
        data: function (provider, e, eOpts) {
            Ext.MessageBox.alert('', e.data.msg);
        }
    },
    id: 'GetMessagePolling'
});
//To initiate a connection
polling.connect();

PollingProvider periodically request URL, when the server response data, the data event fires.

polling.connect() Method will initiate a connection, if you want to close the connection, use polling.disconnect()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Brook at January 12, 2014 - 8:49 PM