Extjs learning notes-9 data model (I)

Source: Internet
Author: User

The data model of Extjs is divided into the following parts:

Data Record
A record in a dataset, including the data definition and value. It is equivalent to an object class.
Data Proxy
The proxy used to obtain data. It is equivalent to Datasource.
Data parser DataReader
Resolves the data obtained by the Proxy and transfers it to the Record and stores it in the Store. It is equivalent to the DataReader of C.
Dataset Store
A set of stored data, similar to the Datatable of C.
The Proxy of Extjs3 has some changes and little information compared with the previous version. In addition, the official documentation is very concise, so that there is no complete example ...... I try my best to understand ......

1. Data Records
A Data Record generally consists of multiple fields. Fields are defined by the Ext. data. Field Class. Field has rich configuration items, so that we have enough information to process our data in weak languages, mainly including:

Name: field name; defaultValue: default value; type: data type, which can be string, int, float, boolean, date, and auto (default ). I will introduce so much, and I will introduce the rest of them when they are used.

To create a data Record class (note that it is not a specific piece of data), you can use the Ext. data. Record. create method. This method accepts the configuration items of the Field class of an array and returns a constructor. Let's look at an example:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
// Create a Record constructor from a description of the fields
Var TopicRecord = Ext. data. Record. create ([// creates a subclass of Ext. data. Record
{Name: 'title '},
{Name: 'author', allowBlank: false },
{Name: 'totalposts', type: 'int '},
{Name: 'lastpost', type: 'date '},
// In the simplest case, if no properties other than name are required,
// A field definition may consist of just a String for the field name.
'Signature'
]);

// Create Record instance
Var myNewRecord = new TopicRecord (
{
Title: 'Do my job please ',
Author: 'noob ',
TotalPosts: 1,
LastPost: new Date (),
Signature :''
},
Id // optionally specify the id of the record otherwise one is auto-assigned
);
Alert (myNewRecord. get ('author '));
</Script>

Here we only demonstrate the most basic functions of Record: defining fields and accessing data. The Record can also be used with the Store to track changes in the Record. Just like the DataTable of C #, you can track the changes of the internal DataRow. Extjs almost changed front-end development to back-end. These content will be introduced again when you introduce the Store.

2. Data proxy
Ext. data. DataProxy is the abstract base class of data proxy. It implements the common public interface of DataProxy. The most important common method of DataProxy is doRequest. After this method is executed, data will be read from various specific data sources. The specific Proxy classes inherited from DataProxy include:

2.1 HttpProxy

This is the most common proxy, which obtains data from a remote server through an http request. The most important configuration item of HttpProxy is to configure the url for obtaining data. HttpProxy not only supports data acquisition, but also supports CRUD operations on data. The api attribute of DataProxy is used to configure the URLs corresponding to these four operations. If not configured, use the url attribute of HttpProxy. For example:
Copy codeThe Code is as follows:
Api :{
Read: '/controller/load ',
Create: '/controller/new', // Server MUST return idProperty of new record

Save: '/controller/Update ',
Destroy: '/controller/destroy_action'
}

Note: The official extjs documentation is rather vague here:

Whether the first of the four operations is read or load ???
After configuring the api, You can execute the doRequest method. The parameters of the doRequest method are complex:

DoRequest (String action, Ext. data. record/Ext. data. record [] rs, Object params, Ext. data. dataReader reader, Function callback, Object scope, Object arg) has the following meanings: action: indicates the operation to be executed, which can be create, read, update, or destroy. Rs: I haven't found any use of this parameter after reading it for a long time ...... Check the source code and find that such an expression url + rs. id appears. This may be used to build a url better for the MVC Architecture Program? Ignore it directly and set it to null. Params: attributes in this object: The value pair will be uploaded to the server as a post/get parameter, which is very useful.

Reader: DataReader, which parses the data returned by the server into a Record array. The following is a more detailed explanation.

Callback: The function executed after the server data is read. This function accepts three parameters: r Ext. Record [], which are returned by the server through the reader array. This is an official statement. In actual tests, it seems that this is only true when the action is read. The following is an introduction; options: the value of the arg parameter. Success: whether the Peugeot or bool is successful. This is also returned by the server.

Scope: scope

Arg: some additional parameters will be passed to the options parameter of callback.

Here is an example of using httpproxy to complete basic CRUD operations. Check the server code first:
Copy codeThe Code is as follows:
<% @ WebHandler Language = "C #" Class = "dataproxy" %>

Using System;
Using System. Web;
Using System. Collections. Generic;

Public class dataproxy: IHttpHandler {
Static List <Student> db = new List <Student> ();
Static dataproxy ()
{
Db. Add (new Student {Id = "1", Name = "Li", Telephone = "1232 "});
Db. Add (new Student {Id = "2", Name = "Wang", Telephone = "5568 "});
Db. Add (new Student {Id = "3", Name = "Chen", Telephone = "23516 "});
Db. Add (new Student {Id = "4", Name = "Zhu", Telephone = "45134 "});
Db. Add (new Student {Id = "5", Name = "Zhou", Telephone = "3455 "});
}
Public void ProcessRequest (HttpContext context ){
String id = context. Request. Params ["id"];
String action = context. Request. Params ["action"];
String result = "{success: false }";
If (action = "create ")
{
}
Else if (action = "read ")
{
Foreach (Student stu in db)
{
If (stu. Id = id)
{
Result = "{success: true, r: [['" + stu. id + "','" + stu. name + "','" + stu. telephone + "']}";
Break;
}
}
}
Else if (action = "update ")
{
}
Else if (action = "delete ")
{
}
Context. Response. ContentType = "text/plain ";
Context. Response. Write (result );
}

Public bool IsReusable {
Get {
Return false;
}
}

Class Student
{
String id;
Public string Id
{
Get {return id ;}
Set {id = value ;}
}
String name;
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
String telephone;

Public string Telephone
{
Get {return telephone ;}
Set {telephone = value ;}
}
}
}

We use a static List to simulate the database. There are four situations in the processing function. The above only implements the read code and returns an array, because the client uses ArrayReader to parse the data. The server-side code is easy to explain. Let's look at the client:
Copy codeThe Code is as follows:
<Head>
<Title> Data Proxy </title>
<Link rel = "Stylesheet" type = "text/css" href = "ext-3.1.0/resources/css/ext-all.css"/>
<Script type = "text/javascript" src = "ext-3.1.0/adapter/ext/ext-base-debug.js"> </script>
<Script type = "text/javascript" src = "ext-3.1.0/ext-all-debug.js"> </script>
<Script type = "text/javascript" src = "ext-3.1.0/src/locale/ext-lang-zh_CN.js"> </script>
<Script type = "text/javascript">
Var Student = Ext. data. Record. create (['id', 'name', 'telphone']);
Var arrayReader = new Ext. data. ArrayReader ({
Root: 'R', idIndex: 0, fields: Student });
Var httpProxy = new Ext. data. HttpProxy ({
Url: 'dataproxy. ashx ',
Api :{
Read: 'dataproxy. ashx? Action = read ',
Create: 'dataproxy. ashx? Action = create ',
Update: 'dataproxy. ashx? Action = Update ',
Destroy: 'dataproxy. ashx? Action = delete'
}
});
Ext. onReady (function (){
Var form = new Ext. FormPanel ({
RenderTo: document. body,
Height: 160,
Width: 400,
Frame: true,
LabelSeparator :':',
LabelWidth: 60,
LabelAlign: 'right ',
DefaultType: 'textfield ',
Items :[
{FieldLabel: 'id ',
Id: 'id'
},
{FieldLabel: 'name ',
Id: 'name'
},
{FieldLabel: 'telphone ',
Id: 'telphone'
}
],
Buttons: [{text: 'read', handler: function (){
HttpProxy. doRequest ('read', null, {id: form. getForm (). findField ('id'). getValue ()}, arrayReader,
Function (r, option, success ){
If (option. arrayData. success ){
Var res = r. records [0];
Ext. Msg. alert ('result From Server', res. get ('id') + ''+ res. get ('name ')
+ ''+ Res. get ('telphone '));
}
Else {
Ext. Msg. alert ('result', 'did not find .');
}

}, This, arrayReader );
}
},
{Text: 'delete'}, {text: 'update'}, {text: 'create'}]
})
});
</Script>
</Head>

Here are some things to explain. First, a Student Record is defined, which is consistent with the server code. Then ArrayReader is defined. ArrayReader reads data in the array. For details about the data format, refer to the server code. It has a root attribute that is very important, specifies the value of the attribute in the json Data Reading (this value is the literal of an array ). idIndex must also be specified, which indicates which field is the primary key. Fields is easy to understand. It reads the Record fields. The order in the array must correspond to the field order of the Record. Otherwise, you can specify the Record through the mapping attribute, for example, {name: 'telphone', mapping: 4} indicates to read the 4th values in the array and put them in the Telephone field. The following describes how to define httpProxy and set the api. Then we create a form:

Add four buttons. First, write the processing function for the Read button: One of doRequest's parameters is 'read', and the second parameter is null, because I don't know how to use it; the third parameter transmits the value of the ID to be queried to the server, and the fourth parameter is a reader. The fifth parameter callback is very important. Here we process the return value of the server. Note: When I set the last parameter to arrayReader, the option parameter value of this function is actually arrayReader. Why should I do this? First, let's make a demonstration. What is the last parameter used? Second, it is because ArrayReader is odd. Note that it does not have public successProperty configuration items, that is to say, it cannot determine the success attribute returned by the server, that is, the success parameter of this callback is always undefined! At first, I thought that the code on my server was incorrect. Later, debug entered the source code and found that it did not process this success attribute. Perhaps the design of ArrayReader is not intended to be used in this environment. But for demonstration, use it like this. In fact, we can still process it without processing the success parameter. ArrayReader has an arrayData attribute. It is a parsed json object. If the returned json string contains the success attribute, this object also has the success attribute. In this way, we can obtain the server return value, likewise, it can process any data returned by the server. Of course, this usage is not available in the document and is only for demonstration. This is the first parameter of callback. In this document, Record [] is used, but it is actually an object. Its record attribute is Record []. I can only say that extjs documents are terrible. Fortunately, this part of the code is very good. If you are interested, you can debug it to have a deeper understanding. All right, everything is ready. Click the Read button and the result is:

This article has come to an end. Several other operations are similar in principle, and suddenly it seems inappropriate to simply use this example for demonstration. Because the Delete and Update servers do not need to return any data, but doRequest forces a DataReader to parse the returned data, which is inconvenient. Maybe other methods of doRequest can be used to operate table-type data. For the CRUD of a single object, you can directly use the lower-layer Ext. ajax method (also described in this article), or use the form method for processing.

This article only briefly introduces the functions and principles of the data model of Extjs. In practice, how to efficiently organize code and transfer data between the server and client is another topic. Extjs is flexible. The communication contract between the client and the server can still be determined by the programmer.

Too long... Next article...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.