ExtJS Note 2 Class System

Source: Internet
Author: User
Tags alphanumeric characters

For the first time in it history, Ext JS went through a huge refactoring from the ground up with the new class system. The new architecture stands behind almost every single class written in Ext JS 4.x, hence it's important to understand it Well before you start coding.

This manual are intended for any developer who wants to create new or extend existing classes in EXT JS 4.x. It ' s divided into 4 sections:

    • Section I: "Overview" explains the need for a robust class system
    • Section II: "Naming conventions" discusses the best practices for naming classes, methods, properties, variables and files .
    • Section III: "Hands-on" provides detailed step-by-step code examples
    • Section IV: "Errors Handling & Debugging" gives useful tips & tricks in how to deal with exceptions
I. Overview

EXT JS 4 ships with more than classes. We have a huge community of more than 200,000 developers to date, coming from various programming backgrounds all over the World. At the a framework, we face a big challenge of providing a common code architecture this is:

    • Familiar and simple to learn
    • Fast-to-develop, easy-to-debug, painless to deploy
    • Well-organized, extensible and maintainable

JavaScript is a classless, prototype-oriented language. Hence by Nature, one of the language's most powerful features is flexibility. It can get the same job done by many different ways, in many different coding styles and techniques. That's feature, however, comes with the cost of unpredictability. Without a unified structure, JavaScript code can be really hard to understand, maintain and re-use.

Class-based programming, on the other hand, still stays as the most popular model of OOP. class-based languages usually require strong-typing, provide encapsulation, and come with standard coding convention. By generally making developers adhere to a large set of principles, written code are more likely to be predictable, extensi BLE and scalable over time. However, they don ' t has the same dynamic capability found in such language as JavaScript.

Each approach had its own pros and cons, but can we had the good parts of both at the same time while concealing the bad Parts? The answer is yes, and we ' ve implemented the solution in Ext JS 4.

II. Naming Conventions naming convention

Using consistent naming conventions throughout your code base for classes, namespaces and filenames helps keep your code o rganized, structured and readable.

1) Classes

Class names may be only contain alphanumeric characters. Numbers is permitted but is discouraged in the most cases, unless they belong to a technical term. Don't use underscores, hyphens, or any other nonalphanumeric character. For example:

The class name should contain only letters and not encourage numbers unless it is part of the term. Do not use underscores, hyphens, and other non-alphabetic characters. For example:

    • MyCompany.useful_util.Debug_Toolbaris discouraged
    • MyCompany.util.Base64is acceptable

Class names should be grouped to packages where appropriate and properly namespaced using object property Dot-notation ( .). At the minimum, there should is one unique top-level namespace followed by the class name. For example:

The class name should be organized into the package.

MyCompany.data.CoolProxyMyCompany.Application

The top-level namespaces and the actual class names should is in camelcased, everything else should is all lower-cased. For example:

The top-level namespaces and class names should be camelcased-style, and the rest are lowercase styles.

MyCompany.form.action.AutoLoad

Classes that is not distributed by Sencha should never use as the Ext top-level namespace.

Non-Sencha published classes, do not use ext as the top-level namespace.

Acronyms should also follow camelcased convention listed above. For example:

Abbreviated words also use camelcased style.

    • Ext.data.JsonProxyInstead ofExt.data.JSONProxy
    • MyCompany.util.HtmlParserInstead ofMyCompary.parser.HTMLParser
    • MyCompany.server.HttpInstead ofMyCompany.server.HTTP
2) Source Files

The names of the classes map directly to the file paths in which they is stored. As a result, there must only is one class per file. For example:

The class name corresponds directly to its file path. Therefore, a class must be a file.

    • Ext.util.Observableis stored inpath/to/src/Ext/util/Observable.js
    • Ext.form.action.Submitis stored inpath/to/src/Ext/form/action/Submit.js
    • MyCompany.chart.axis.Numericis stored inpath/to/src/MyCompany/chart/axis/Numeric.js

path/to/srcIs the directory of your application ' s classes. All classes should stay under this common root and should being properly namespaced for the best development, maintenance and Deployment experience.

3) Methods and Variables
    • Similarly to class names, method and variable names if only contain alphanumeric characters. Numbers is permitted but is discouraged in the most cases, unless they belong to a technical term. Don't use underscores, hyphens, or any other nonalphanumeric character. The naming rules for methods and variables are basically consistent with the class name rules.

    • Method and variable names should always is in camelcased. This also applies to acronyms. Method and variable names are always camelcased, and abbreviations are the same.

    • Examples

      • Acceptable method Names:encodeusingmd5 () gethtml () instead of gethtml () Getjsonresponse () instead of getJSONResponse() parseXmlContent() instead of Parsexmlconten T ()
      • Acceptable variable Names:var isgoodname var base64encoder var xmlReader var httpserver
4) Properties
    • Class property names follow the exact same convention with methods and variables mentioned above, except Y is static constants. Attribute naming rules are basically consistent with methods and variable naming rules

    • Static class properties that is constants should is all upper-cased. For example: Static class properties with a constant value, all using uppercase.

      • Ext.MessageBox.YES = "Yes"
      • Ext.MessageBox.NO = "No"
      • MyCompany.alien.Math.PI = "4.13"
III. Hands-on hands 1. Declaration1.1) The old

If you had ever used any previous version of Ext JS, you were certainly familiar with to Ext.extend create a class:

var Mywindow = Ext.extend (Object, {...});

This approach are easy-to-follow to create a new class, inherits from another. Other than direct inheritance, however, we didn ' t has a fluent API for other aspects of class creation, such as Configura tion, statics and mixins. We'll be reviewing these items in details shortly.

Let's take a look at another example:

My.cool.Window = Ext.extend (Ext.window, {...});

In this example we want to namespace our new class, and make it extend from Ext.Window . There is concerns we need to address:

    1. My.coolNeeds to is an existing object before we can assign as it property Window
    2. Ext.WindowNeeds to exist/loaded on the page before it can referenced

The first item is usually solved with Ext.namespace (aliased by Ext.ns ). This method recursively transverse through the object/property tree and create them if they don ' t exist yet. The boring part is need to remember adding them above all the time Ext.extend .

Ext.ns (' my.cool '= Ext.extend (Ext.window, {...});

The second issue, however, is isn't easy to address because Ext.Window might depend on many other classes that it Directly/indi Rectly inherits from, and in turn, these dependencies might depend on other classes to exist. For this reason, applications written before EXT JS 4 usually include the whole library in the form of ext-all.js even though T Hey might only need a small portion of the framework.

1.2) The New way

EXT JS 4 eliminates all those drawbacks with just one single method you need to remember for class creation: Ext.define . Its basic syntax is as follows:

Just remember one method Ext.define .

Ext.define (ClassName, Members, onclasscreated);

    • className: The class name
    • membersIs an object represents a collection of class Key-value pairs JSON form
    • onClassCreatedis a optional function callback to being invoked when any dependencies of this class was ready, and the class itself was full Y created. Due to the new asynchronous nature of class creation, this callback can is useful in many situations. These will is discussed further in the section IV callback function, which is called when the class is created.

Example:

Ext.define (' My.sample.Person ', {    ' Unknown ',    function(name) {         if (name) {            this. Name = name;        }    },    function( FoodType) {        alert (this. Name + "is eating:" + FoodType);    });  var aaron = Ext.create (' My.sample.Person ', ' Aaron ');    Aaron.eat (//  alert ("Aaron is Eating:salad");

Note We created a new instance of My.sample.Person using the Ext.create() method. We could have used the new keyword ( new My.sample.Person() ). However it is recommended-get in the habit of all using Ext.create since it allows you-take advantage of dynamic Loadi Ng. for + info on dynamic loading see the Getting Started Guide

Note that we use the Ext.create() method to create an object, and it is recommended that you always create the object in this way, because it provides the ability to load dynamically.

2. Configuration

In Ext JS 4, we introduce a dedicated property that config gets processed by the powerful Ext.class pre-processors before t He class is created. Features include:

In ext JS 4, a dedicated config property is introduced, which is pre-processing before the class is created by the Ext.class implementation. The features that are included are:

    • Configurations is completely encapsulated from the other class member configuration is fully encapsulated for other classes of members
    • Getter and setter, methods for every config property is automatically generated into the class ' prototype during class CR   Eation if the class does not has these methods already defined. Getter and setter methods are automatically generated into the class
    • A apply method is a also generated for every config property. The auto-generated setter method calls the apply method internally before setting the value. Override the apply method for a config property if you need to run custom logic before setting the value. If apply does not return a value then the setter would not set the value.   For a example see applyTitle below. an apply method is also generated for each configuration property. The automatically generated set-up method calls the Apply method internally before assigning a value. If you need to run custom logic before assigning values, you can override the Apply method. If apply does not return a value, the set will not be assigned a value. Here is an example of apply.

Here's an example:

Ext.define (' My.own.Window ', {    /** @readonly*/IsWindow:true, config: {title:' Title here ', Bottombar: {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 {            returntitle; }}, Applybottombar:function(Bottombar) {if(Bottombar) {if(! This. Bottombar) {                returnExt.create (' My.own.WindowBottomBar ', Bottombar); }            Else {                 This. Bottombar.setconfig (Bottombar); }        }    }});/** A Child component to complete the example.*/Ext.define (' My.own.WindowBottomBar ', {config: {height:undefined, resizable:true    }});

And here's an example's it can be used:

varMywindow = ext.create (' My.own.Window '), {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}); alert (Mywindow.getbottombar (). GetHeight ()); //Alerts

3. Statics

Static statics members can defined using the CONFIG. statics configuration item to define

Ext.define (' computer ', {statics: {instancecount:0, Factory:function(brand) {//' This ' 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 a instance refers to its class         This. Self.instancecount + +; }});varDellcomputer = computer.factory (' Dell ');varApplecomputer = 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. Errors handling & Debugging error handling and commissioning

EXT JS 4 includes some useful features that'll help you with debugging and error handling.

    • You can use a to Ext.getDisplayName() get the display name of any method. This was especially useful for throwing errors, that has the class name and method name in their description:

      Throw New Error (' [' + ext.getdisplayname (Arguments.callee) + '] Some message here ');

    • When a error is thrown in any method of any class defined using Ext.define() , you should see the method and class names in the C All stacks if you are using a WebKit based browser (Chrome or Safari). For example, here's what it would look like in Chrome:

See Also
    • Dynamic Loading and the New Class System
    • Classes in Ext JS 4:under the Hood
    • The Class Definition Pipeline

ExtJS Note 2 Class System

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.