EXT Introduction)

Source: Internet
Author: User

Whether you are new to the ext library or want to know Ext, this articleArticleContent is suitable for you. This article will briefly introduce several basic concepts of Ext, and how to quickly create and run a dynamic page, assuming that the reader has some JavaScript experience and a beginner understanding of HTML Dom. Otherwise, read the Javascript resources for beginners.

Download ext
If you have never downloaded the latest version of ext http://extjs.com/downloads.

There are several different elastic options for your download needs. Generally, the most stable version is the choice of many people. After downloading and unpackage, the example folder is a great place to explore ext!

Start!
We will use ext to complete some JavaScript tasks.

The zip file consists of extstart.html, extstart.js, and extstart.css. Decompress these three files to the ext installation directory (for example, ext is in "C: \ code \ ext \ V1.0, create the directory "tutorial" in "V1.0 ". Double-click extstart.htm, and then open the startup page in your browser. There should be a message telling you that the configuration is complete. If a javascript error occurs, follow the instructions on the page.

In your commonly used ide or text editor, open extstart. js to see:

Ext. onready may be your first method. This method ensures that all elements on the page can be referenced by a script after the current Dom is loaded ). You can delete alert () and add some usefulCodeTry:

Ext. onready (function (){
Alert ("Congratulations! You have ext configured correctly! ");
});

Element: ext Core
Most JavaScript operations need to obtain a reference element on the page, so that you can do interesting things. The traditional JavaScript method obtains DOM nodes by ID:

VaR mydiv = Document. getelementbyid ('mydiv ');

This is no problem, but returning an object (DOM node) is not very powerful and easy to use. To use that node to do something, you will need to write a lot of Custom Code. In addition, for the differences between different types of browsers, it is really big to deal.

Enter the Ext. Element Object. The element is indeed the heart of Ext, which is involved in accessing elements and completing some actions. The element API is the basis of the entire ext library. If you only want to know a class in ext, element must be the first choice!

Obtain an ext elementby ID (for example, the first page extstart.htm contains a DIV, whose ID is "mydiv", and then add the following statement to extstart. JS ):

Ext. onready (function () {var mydiv = ext. Get ('mydiv ');});

Let's look back at the Element Object and find something interesting?

> Element contains common Dom methods and attributes, providing a fast, unified, and cross-browser interface (if you use element. dom, you can directly access the underlying Dom node .);
> The element. Get () method has a built-in cache, which greatly improves the efficiency of multiple accesses to the same object;
> Built-in common Dom node actions, including cross-browser location, size, animation, drag and drop (Add/Remove CSS classes, Add/Remove event handlers, positioning, sizing, animation, drag/drop ).

This means that you can use the smallest code to do a variety of things. Here is just a simple example (the complete list is in elementapi ).

In extstart. JS, add:

Mydiv. Highlight (); // highlighted in yellow and then fade away
Mydiv. addclass ('red'); // Add a custom CSS class (defined in extstart.css)
Mydiv. Center (); // center the element in the view
Mydiv. setopacity (. 25); // make the element translucent

Get multiple DOM nodes
Generally, you cannot obtain multiple DOM nodes by ID. It may be because you do not set the ID, or you do not know the ID, Or you directly reference too many elements by ID. In this case, you do not need to use ID as the basis for obtaining elements, and may use attribute or CSS classname instead. Based on the above reasons, ext introduces a very powerful Dom selector library called domquery.

Domquery can be used as a separate library, but is often used in Ext. You can obtain multiple elements in the context and call them through the element interface. Fortunately, the element object itself has the element. selcect method to implement the query, that is, internally calling domquery to select the element. In this simple example, extstart.htm contains several paragraphs (<p> tags), none of which have IDs, and you want to easily obtain each segment through an operation and perform all their actions, you can do this:

// Highlight each segment
Ext. Select ('P'). Highlight ();

Domquery selection parameters are a long array, including W3C css3 Dom selector, basic xpatch, HTML attributes, and more, see the domquery API documentation for details about this powerful library.

RESPONSE event
By this example, all the code we have written is put in onready, that is, when the page is loaded, it will always be executed immediately, and the function is relatively simple-in this case, you will know, how to respond to an action or event to execute what you want to do is assign a function and define an event handler event processor to respond. Let's start with this simple example. Open extstart.htm and edit the following code:

Ext. onready (function (){
Ext. Get ('myclick'). On ('click', function (){
Alert ("You clicked the button ");
});
});

After the page is loaded, the code will still be executed. However, the difference is that the function containing alert () is defined, but it will not be executed immediately. It is allocated to the Click Event of the button. In plain text, it is used to obtain the reference of the 'myottom 'element, listen to any element being clicked, and assign a function to prepare any clicked element.

Element. Select can also do the same thing, that is, it is used to obtain a group of elements. In the next example, a section in the page is displayed after it is clicked:

Ext. onready (function (){
Ext. Select ('P'). On ('click', function (){
Alert ("You clicked a paragraph ");
});
});

In these two examples, the function processed by the event is a few simple statements without the function name. This type of function is called "anonymous function", which is a function without a name. You can also assign an event handler with a name, which is useful for code reuse or multiple events. The next example is equivalent to the previous example:

Ext. onready (function (){
VaR paragraphclicked = function (){
Alert ("You clicked a paragraph ");
}
Ext. Select ('P'). On ('click', paragraphclicked );
});

So far, we have known how to execute an action. But when an event is triggered, how do we know the specific elements that the event handler is used to execute? It is very simple to clarify this, element. the on method is passed into the function of even handler (we will discuss the first parameter here, but you should browse the API documentation to learn more about even handler ). In our previous example, the function ignores these parameters, but there are a few changes here-we provide more in-depth functional control. It must be noted first that this is actually an ext event object, a cross-browser and more controlled event. For example, you can use the following statement to restore the specified Dom node of the event:

Ext. onready (function (){
VaR paragraphclicked = function (e ){
Ext.get(e.tar get). Highlight ();
}
Ext. Select ('P'). On ('click', paragraphclicked );
});

Note that the DOM node is specified, so we first restore it to an appropriate element and then execute the event to be completed. In this example, we can see that the Section is highlighted.

Use Widgets
(Widget originally meant "Small device", which now refers to the UI control on the page)
In addition to the core JavaScript library we have discussed, ext now includes a series of front-end javascirptui component libraries. Take the most common widget as an example.

MessageBox
Compared to the slightly dull "hellowolrd" message window, we made a few changes. The code we wrote earlier is that clicking a paragraph is highlighted, and now we click a paragraph, the Section content is displayed in the message window.
In the preceding paragraphclicked function, run the following code:

Ext.get(e.tar get). Highlight ();

Replace:

VaR paragraph = ext.get(e.tar get );
Paragraph. Highlight ();
Ext. MessageBox. Show ({
Title: 'Paragraph clicked ',
MSG: paragraph. Dom. innerhtml,
Width: 400,
Buttons: Ext. MessageBox. OK,
Animel: paragraph
});

Some new concepts are discussed here. In the first line, we created a local variable to save the reference of an element, that is, the clicked Dom node (in this example, we always use the section paragrah, the event is associated with the <p> tag ). Why? Well... observe the Code above. We need to reference the same element to highlight and use the same element as a parameter in MessageBox.
Generally, repeated use of the same value or object is a bad way. Therefore, as a good OOP developer, it should be allocated to a local variable, use this variable repeatedly!

Now, observe the call of MessageBox and use it as a demonstration of the new concept. At first glance, this is like a series of parameters passed into the method, but carefully, this is a very special syntax. In fact, only one parameter is input to MessageBox. Show: an object literal, which contains a set of attributes and attribute values. In JavaScript, object literal is dynamic. You can use {And} to create a typical object at any time ). The character is composed of a series of name/value Attributes. The attribute format is [property name]: [property value]. In Ext, you will often encounter the syntax of this mode, so you should consume this knowledge!
What is the reason for using object literal? The main reason is "flexibility". You can add or delete attributes at any time, or insert attributes in sequence. The method does not need to be changed. This is also the case of multiple parameters, which brings a lot of convenience to the end developer (MessageBox. Show () in this example ()). For example, the foo. Action method here has four parameters, and only one is required. In this example, the code you imagine may be Foo. action (null, 'Hello ')., if the method is written using object literal, it is like this, foo. action ({param4: 'hello'}), which is easier to use and easy to read.

Gird
Gird is one of the most popular widgets in ext. Well, let's see how to easily create a gird and run it. Replace all the statements in extstart. js with the following code:

Ext. onready (function (){
VaR mydata = [
['Apple', 29.89, 0.24, 0.81, '2017 am '],
['Text', 83.81, 0.28, 0.34, '2017 am '],
['Google ', 71.72, 0.02, 0.03, '2017 am'],
['Microsoft ', 52.55, 0.01, 0.02, '2017 am'],
['Yahoo! ', 29.01, 0.42, 1.47, '2017 am']
];

VaR DS = new Ext. Data. Store ({
Proxy: New Ext. Data. memoryproxy (mydata ),
Reader: New Ext. Data. arrayreader ({ID: 0 },[
{Name: 'company '},
{Name: 'price', type: 'float '},
{Name: 'change', type: 'float '},
{Name: 'pctchang', type: 'float '},
{Name: 'lastchang', type: 'date', dateformat: 'n'/j h: '}
])
});
DS. Load ();

VaR colmodel = new Ext. Grid. columnmodel ([
{Header: "company", width: 120, sortable: True, dataindex: 'company '},
{Header: "price", width: 90, sortable: True, dataindex: 'price '},
{Header: "change", width: 90, sortable: True, dataindex: 'change '},
{Header: "% change", width: 90, sortable: True, dataindex: 'pctchang '},
{Header: "Last updated", width: 120, sortable: True,
Renderer: Ext. util. format. daterenderer ('m/D/Y'), dataindex: 'lastchange '}
]);

VaR grid = new Ext. Grid. Grid ('grid-example ', {DS: ds, CM: colmodel });
Grid. Render ();
Grid. getselectionmodel (). selectfirstrow ();
});

This looks complicated, but in fact it adds up to only seven lines of code. The first line creates an array and acts as the data source. In actual cases, you may obtain dynamic data from the database or WebService. Then, we create and load the data store, and the data store will tell the underlying library of ext to take over and format the data. Next, we define a column model to easily deploy each column of gird parameters. Finally, we generate this gird and pass in the Data Store and column models to render and select the first row. Isn't it too difficult? If everything goes well, you will see something like this:

Of course, you may not fully understand the details of this Code (for example, what is memoryproxy ?) But it doesn't matter first. The purpose of this example is to tell you how to use a small amount of code to create a rich UI with Multiple Functional UI components-this is entirely possible, with more details, let readers learn by themselves. There are many resources for learning grid. EXT grid tutorial, cross gird demo, and grid API documentation.

There are more ..
This is just the tip of the iceberg. There are also a dozen of UI widgets available for calling, such as layouts, tabs, menus, toolbars, dialogs, and tree view. See examples in the API documentation.

Use Ajax
After some pages are completed, you have understood the control principle between pages and scripts (interact ). Next, you want to know how to exchange data with the remote server. It is common to load data from the database or save the data to the database. Ajax is used to asynchronously exchange data without refreshing JavaScript. Ext has built-in excellent Ajax support. For example, a common user operation is to asynchronously send something to the server, and then the UI elements are updated based on the response. This is a table containing text input. A divis used to display the message (messages). You can add the following code to extstart.html, but you must access the server ):

< Div ID = "MSG" Style = "Visibility: hidden" > </ Div >  
Name: < Input Type = "Text" ID = "Name"   /> < BR />  
< Input Type = "Button" ID = "Okbutton" Value = "OK"   />

Next, we add the JavaScript code for processing the exchange data to the extstart. js file (overwrite it with the following code ):

Ext. onready (function (){
Ext. Get ('okclick'). On ('click', function (){
VaR MSG = ext. Get ("MSG ");
MSG. Load ({
URL: [server url], // change to your url
Params: "name =" + Ext. Get ('name'). Dom. value,
Text: "Updating"
});
MSG. Show ();
});
});

This mode looks familiar! First, obtain the button element and add the event listening. In event handler, we use an ext built-in class that handles Ajax requests, accepts responses, and updates another element, called updatemanager. Updatemanager can be used directly or accessed through the load method of element, as we do now (in this example, the element is the DIV of "MSG ). When the element. load method is used, the request will be processed and sent, waiting for the response from the server to automatically replace the innerhtml of the element. You can simply input the server URL address and add a string parameter to process this request (in this example, the parameter value comes from the value of the "name" element ), the text value is the text prompted when the request is sent. The DIV of the MSG is displayed after the request is sent (because it is hidden by default at the beginning ). Of course, like most ext components, updatemanager has many optional parameters, and different Ajax requests have different solutions. Here we only show the simplest one.

PHP

<?  
If ( Isset ( $ _ Get [ ' Name ' ])
{
Echo   ' From Server: ' . $ _ Get [ ' Name ' ];
}
?>

ASP. NET

Protected   Void Page_load ( Object Sender, eventargs E)
{
If (Request [ " Name " ] ! =   Null )
{
Response. Write ( " From Server: "   + Request [ " Name " ]);
Response. End ();
}
}

Cold fusion

< Cfif Structkeyexists (URL, "name ") >  
< Cfoutput > From server: # URL. name # </ Cfoutput >
</ Cfif >

The last question about Ajax is that the server actually processes requests and returns (resposne. This process will be a server page, a servlet, an HTTP processor, a WebService, or even a Perl or CGI script, that is, any server can process HTTP requests. Unexpectedly, the server returns something about the server and cannot provide a standard example to cover all possibilities. (This code outputs the value of 'name' that we just passed in to the client, that is, what is sent and what is returned ).

The real challenge of using Ajax is the manual code that needs to be properly processed and formatted as a data structure available for the server. There are several formats for people to choose from (the most commonly used is JSON/XML ). Because ext is a language neutral to the server, libraries in other specific languages can also be used for ext to process Ajax services. As long as the page receives the result in a suitable data format, ext will never ask the server! This issue is beyond the scope of this article. We recommend that you use ajax to go deep into the ext Ajax tutorial.

What is next?
Now you have a glimpse of ext and know what she can do. The following resources help you further understand the overall picture:

Additional ext tutorial
ProgramMember API documentation
User Forum
 
Source: http://extjs.com/tutorial/ext

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.