Ext JS 4 Official Document 3-class system overview and practices

Source: Internet
Author: User
Tags alphanumeric characters

Ext JS 4 restructured the class system from the underlying layer. This is the first time in the history of Ext JS to reconstruct the class system. The new architecture is applied to almost every Ext JS 4 class, so it is very important that you have a certain understanding of it before you start coding.
This Manual applies to any developer who wants to create a new class or inherit the existing classes in Ext JS 4. It is divided into four parts:
Part 1: "Overview" -- explains the necessity of creating a strong Class System
Part 2: "naming conventions" -- discusses the best naming conventions for classes, methods, attributes, variables, and files
Part 3: "practice" -- provides detailed sample code step by step.
Part 4: "error handling and debugging"-provides useful tips and skills on how to handle exceptions

I. Overview
Ext JS 4 has over 300 classes. So far, we already have a huge community of over 200,000 developers who come from various programming backgrounds around the world. For such a large-scale framework, we are faced with a huge challenge to provide a general code architecture:
Friendly and easy to learn
Rapid development, easy debugging, and easy deployment
Good organization, scalability and Maintenance
JavaScript is a non-typed, prototype-oriented language. Flexibility is one of the most powerful features of this language. It can use different encoding styles and techniques in different ways to complete the same job. However, this feature brings an unpredictable price. Without a unified structure, JavaScript code is hard to understand, maintain, and reuse.
Class-based programming, in other words, uses the most popular OOP model. A class-based language is usually a strong type language. It provides encapsulation and has standard encoding conventions. Generally, developers are allowed to follow a set of unified encoding rules, so that the written code is more predictable, scalable, and extensible. However, they do not have the same dynamic capabilities as JavaScript.
Each method has its own advantages and disadvantages, but can we use both of them to hide their disadvantages? The answer is yes. We have implemented this solution in Ext JS 4.

Ii. Naming rules
Always use consistent naming rules based on classes, namespaces, and file names in your code, which helps keep your code organized, structured, and readable.
1) Class
A class name can only contain letters, numbers, and numbers. In most cases, they are not allowed unless they belong to a technical term. Do not use underscores, hyphens, or any other non-alphanumeric characters. For example:
MyCompany. useful_util.Debug_Toolbar is not allowed
MyCompany. util. Base64 is acceptable
The class name should be placed in an appropriate namespace by using the vertex expression (.) attribute of the object. At least, the class name should have a unique top-level namespace. For example:
MyCompany. data. CoolProxy
MyCompany. Application
Top-level namespaces and class names should both adopt the camper method, and all others should be in lower case. For example:
MyCompany. form. action. AutoLoad
Classes not published by Ext JS of Sencha cannot use Ext as the top-level namespace.
The acronyms should also follow the aforementioned camper naming rules. For example:
Ext. data. JsonProxy replaces Ext. data. JSONProxy
MyCompany. util. HtmlParser replaces MyCompary. parser. HTMLParser
MyCompany. server. Http replaces MyCompany. server. HTTP
2) source file
The class name is directly mapped to the file path where they are stored. Therefore, each file can only have one class. For example:
Ext. util. Observable is stored in/to/src/Ext/util/Observable. js
Ext. form. action. Submit is stored in/to/src/Ext/form/action/Submit. js.
MyCompany. chart. axis. Numeric stored in/to/src/MyCompany/chart/axis/Numeric. js
Path/to/src is the root directory of your application's class. All classes should be placed under this common root directory.
3) methods and variables
Similar to class names, method and variable names can only contain letters, numbers, and numbers are not allowed in most cases unless they belong to a technical term. Do not use underscores, hyphens, or any other non-alphanumeric characters.
Methods and variable names should always be in the camper format, which also applies to acronyms.
Example:
Acceptable Method Name: encodeUsingMd5 (), getHtml () replaces getHTML (), getJsonResponse () replaces getJSONResponse (), and parseXmlContent () replaces parseXMLContent ()
Acceptable variable names: var isGoodName, var base64Encoder, var xmlReader, var httpServer
4) attributes
The class property name follows the same naming rules as the preceding method and variable, except for static constants.
Static class attributes, that is, constants should all be capitalized. For example:
Ext. MessageBox. YES = "Yes"
Ext. MessageBox. NO = "No"
MyCompany. alien. Math. PI = "4.13"

Iii. Practice
1. Statement
1.1) Old Method
If you have used any previous version of Ext JS, you must be familiar with using Ext. extend to create classes:
Var MyWindow = Ext. extend (Object ,{...});
This method is easy to create a new class that inherits from other classes. However, apart from direct inheritance, we do not have a good API to create other aspects of the class, such as configuration, static configuration, and mixed class, we will review them in detail later.
Let's look at another example:
My. cool. Window = Ext. extend (Ext. Window ,{...});
In this example, we want to create a new class with a namespace and inherit Ext. Window. There are two problems to solve:
My. cool must be an existing namespace object so that we can allocate Window as its attribute.
Ext. Window must exist and be loaded to reference it.
The first point is commonly used Ext. namespace (alias: Ext. ns) to solve the problem. This method recursively creates non-existent objects, and the annoying thing is that you must always remember to add them to Ext. before extend:
Ext. ns ('My. cool '); My. cool. Window = Ext. extend (Ext. Window ,{...});
However, the second problem is not easy to solve, because Ext. window may depend on many other classes. It may inherit directly or indirectly from those dependent classes, and these dependent classes may depend on other classes. For this reason, applications written prior to Ext JS 4 usually introduce the entire library file ext-all.js, although it may only need a small part of it.
1.2) New Method
Ext JS 4 eliminates all these shortcomings. You only need to remember that the only method to create a class is Ext. define. Its basic syntax is as follows:
Ext. define (className, members, onClassCreated );
ClassName: Class Name
Members is a large object that represents a set of class members and is a series of key-value pairs.
OnClassCreated is an optional callback function. It is called when all dependencies of the class are ready and the class is completely created. This callback function is useful in many cases and will be discussed in the fourth part.
Example:Copy codeThe Code is as follows: Ext. define ('My. sample. person ',{
Name: 'unknown ',
Constructor: function (name ){
If (name ){
This. name = name;
}},
Eat: function (foodType ){
Alert (this. name + "is eating:" + foodType );}});
Var aaron = Ext. create ('My. sample. Person ', 'Aaron ');
Aaron. eat ("Salad"); // alert ("Aaron is eating: Salad ");

Note that we use Ext. create () to create an instance of My. sample. Person. Of course, we can also use the new keyword (new My. sample. Person (). However, we recommend that you always use Ext. create because it can use the dynamic loading function. For more information about dynamic loading, see the Ext JS 4 Getting Started Guide.

2. Configuration
In Ext JS 4, we introduced a special config attribute, which will be processed by the powerful pre-processor Class Ext. Class before the Class is created, with the following features:
Configurations are completely encapsulated from other class members.
The getter and setter methods of each config attribute are automatically generated in the class prototype. If these methods are not defined in the class
At the same time, an apply method will be generated for each config attribute. The automatically generated setter method will call this apply method before setting the value internally. If you want to run the custom logic before setting the value, you can overwrite the apply method. If apply does not return a value, the setter method does not set a value. Let's take a look at the following applyTitle method:
The following example defines a new class:Copy codeThe Code is as follows: Ext. define ('My. own. Window', {/** @ readonly */
IsWindow: true,
Config :{
Title: 'title Here ',
BottomBar :{
Enabled: true,
Height: 50,
Resizable: false }},
Constructor: function (config ){
This. initConfig (config );},
ApplyTitle: function (title ){
If (! Ext. isString (title) | title. length = 0 ){
Alert ('error: Title must be a valid non-empty string ');
} Else {
Return title;
}},
ApplyBottomBar: function (bottomBar ){
If (bottomBar & bottomBar. enabled ){
If (! This. bottomBar ){
Return Ext. create ('My. own. WindowBottomBar ', bottomBar );
} Else {
This. bottomBar. setConfig (bottomBar );
}
}
}});

The following is an example of how to use this new class:Copy codeThe Code is as follows: var myWindow = Ext. create ('My. own. Windows ',{
Title: 'Hello world ',
BottomBar :{
Height: 60 }});
Alert (myWindow. getTitle (); // alerts "Hello World"
MyWindow. setTitle ('Something new ');
Alert (myWindow. getTitle (); // alerts "Something New"
MyWindow. setTitle (null); // alerts "Error: Title must be a valid non-empty string"
MyWindow. setBottomBar ({height: 100}); // Bottom bar's height is changed to 100

3. Static Configuration
Static configuration members can use the statics attribute to define:Copy codeThe Code is as follows: Ext. define ('computer ',{
Statics :{
InstanceCount: 0,
Factory: function (brand ){
// 'Like' in static methods refer to the class itself
Return new this ({brand: brand });}},
Config :{
Brand: null },
Constructor: function (config ){
This. initConfig (config );
// The 'Self 'property of an instance refers to its class
This. self. instanceCount ++ ;}});
Var dellComputer = Computer. factory ('Dell '); var appleComputer = Computer. factory ('mac ');
Alert (appleComputer. getBrand ());
// Using the auto-generated getter to get the value of a config property. Alerts "Mac"
Alert (Computer. instanceCount );
// Alerts "2"

Iv. Error Handling and debugging
Ext JS 4 contains some useful features that can help you debug and handle errors:
You can use Ext. getDisplayName () to obtain the display name of any method. This is particularly useful. When an error is thrown, it can be used to display the class name and method name in the error description:
Throw new Error ('[' + Ext. getDisplayName (arguments. callee) + '] Some message here ');
When an error occurs from. when any method of the class defined by define () is thrown, if you use a WebKit-based browser (Chrome or Safari), you will see the method name and class name in the call stack. For example, the stack information shown in Chrome is as follows:

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.