For the first time in its 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 is 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 on how to deal with exceptions

I. Overview

Ext JS 4 ships with more than 300 classes. We have a huge community of more than 200,000 developers to date, coming from various programming backgrounds all over the world. At that scale of a framework, we face a big challenge of providing a common code architecture that 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 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 is more likely to be predictable, extensible and scalable over time. However, they don't have the same dynamic capability found in such language as JavaScript.

Each approach has its own pros and cons, but can we have 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    命名约定

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

1) Classes

Class names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character. For example:

类名应该只包含字母,不鼓励用数字,除非它是术语的一部分。不要使用下划线、连字符等其它非字母字符。例如:

  • MyCompany.useful_util.Debug_Toolbar is discouraged
  • MyCompany.util.Base64 is acceptable

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

类名称应该被组织到包中。

MyCompany.data.CoolProxy
MyCompany.Application

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

顶级命名空间和类名应该是CamelCased风格的,其它都是小写风格。

MyCompany.form.action.AutoLoad

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

非Sencha发布的类,不要使用Ext做为顶级命名空间。

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

缩写词语也使用CamelCased风格。

  • Ext.data.JsonProxy instead of Ext.data.JSONProxy
  • MyCompany.util.HtmlParser instead of MyCompary.parser.HTMLParser
  • MyCompany.server.Http instead of MyCompany.server.HTTP

2) Source Files

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

类名直接与其文件路径对应。因此,必须一个类一个文件。

  • Ext.util.Observable is stored in path/to/src/Ext/util/Observable.js
  • Ext.form.action.Submit is stored in path/to/src/Ext/form/action/Submit.js
  • MyCompany.chart.axis.Numeric is stored in path/to/src/MyCompany/chart/axis/Numeric.js

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

3) Methods and Variables

  • Similarly to class names, method and variable names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character.方法和变量的命名规则与类名规则基本一致。

  • Method and variable names should always be in camelCased. This also applies to acronyms.方法和变量名始终都是camelCased,缩写词也是这样。

  • Examples

    • Acceptable method names: encodeUsingMd5() getHtml() instead of getHTML() getJsonResponse() instead of getJSONResponse() parseXmlContent() instead ofparseXMLContent()
    • 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 the case when they are static constants.属性命名规则与方法、变量命名规则基本一致

  • Static class properties that are constants should be all upper-cased. For example:值为常量的静态类属性,都使用大写。

III. Hands-on   动手

1. Declaration

1.1) The Old Way

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

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

This approach is easy to follow to create a new class that inherits from another. Other than direct inheritance, however, we didn't have a fluent API for other aspects of class creation, such as configuration, statics and mixins. We will 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 are two concerns we need to address:

  1. My.cool needs to be an existing object before we can assign Window as its property
  2. Ext.Window needs to exist / loaded on the page before it can be 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 you need to remember adding them above Ext.extend all the time.

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

The second issue, however, is not easy to address because Ext.Window might depend on many other classes that it directly / indirectly inherits from, and in turn, these dependencies might depend on other classes to exist. For that reason, applications written before Ext JS 4 usually include the whole library in the form of ext-all.js even though they 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:

只需记住一个方法 Ext.define.

Ext.define(className, members, onClassCreated);
  • className: The class name  类名称
  • members is an object represents a collection of class members in key-value pairs   json形式的类表示
  • onClassCreated is an optional function callback to be invoked when all dependencies of this class are ready, and the class itself is fully created. Due to the new asynchronous nature of class creation, this callback can be useful in many situations. These will be discussed further in Section IV   回调函数,类创建后会调用。

Example:

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 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 to get in the habit of always using Ext.create since it allows you to take advantage of dynamic loading. For more info on dynamic loading see the Getting Started guide

注意,我们使用了Ext.create()方法来创建对象,推荐始终用这种方式来创建对象,因为它提供了动态加载的能力。

2. Configuration   配置

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

在EXT JS 4中,引入了专用的config属性,它通过Ext.Class实现类创建之前的预处理。包含的特性有:

  • Configurations are completely encapsulated from other class members 配置对于其它类成员完全封装
  • Getter and setter, methods for every config property are automatically generated into the class' prototype during class creation if the class does not have these methods already defined.   getter和setter方法会自动生成到类中
  • An apply method is 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 will not set the value. For an example see applyTitle below.   一个apply方法也为每个配置属性生成。自动生成的设置者方法在赋值前在内部调用apply方法。如果你需要在赋值前运行自定义逻辑,可以重写apply方法。如果apply不返回值,那么设置者将不赋值。下面是一个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 {
return title;
}
}, applyBottomBar: function(bottomBar) {
if (bottomBar) {
if (!this.bottomBar) {
return Ext.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 of how it can be used:

var myWindow = 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 100

3. Statics

Static members can be defined using the statics config    静态成员可以使用statics 配置项来定义

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 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. Errors Handling & Debugging   错误处理和调试

Ext JS 4 includes some useful features that will help you with debugging and error handling.

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

    throw new Error('['+ Ext.getDisplayName(arguments.callee) +'] Some message here');
  • When an error is thrown in any method of any class defined using Ext.define(), you should see the method and class names in the call stack if you are using a WebKit based browser (Chrome or Safari). For example, here is what it would look like in Chrome:

See Also

ExtJS笔记2 Class System的更多相关文章

  1. EXTJS 5 学习笔记1 - Class System

    1. Name Conventions 命名规范      1) Classes 类          a. 类名只能包含数字字母 only contain alphanumeric characte ...

  2. ExtJS笔记 Using Events

    Using Events The Components and Classes of Ext JS fire a broad range of events at various points in ...

  3. ExtJS笔记5 Components

    参考 :http://blog.csdn.net/zhangxin09/article/details/6914882 An Ext JS application's UI is made up of ...

  4. extjs笔记

      1.    ExtJs 结构树.. 2 2.    对ExtJs的态度.. 3 3.    Ext.form概述.. 4 4.    Ext.TabPanel篇.. 5 5.    Functio ...

  5. ExtJS笔记 Reader

    Readers are used to interpret data to be loaded into a Model instance or a Store - often in response ...

  6. ExtJS笔记 Store

    The Store class encapsulates a client side cache of Model objects. Stores load data via a Proxy, and ...

  7. ExtJS笔记 Ext.data.Model

    A Model represents some object that your application manages. For example, one might define a Model ...

  8. ExtJS笔记 Ext.Loader

    Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most co ...

  9. ExtJS笔记 Tree

    The Tree Panel Component is one of the most versatile Components in Ext JS and is an excellent tool ...

随机推荐

  1. 如何解决adb devices 端口被占用的问题zz

    在win xp ,win 7 上使用adb时, 越来越多的人出现了 adb devices 命令长时间无响应.adb start-server 失败.eclipse adt初始化时卡在dbms-ini ...

  2. 【ACM - 搜索模板】

    [广搜模板] #include <iostream> #include <stdio.h> #include <string.h> #include <que ...

  3. 无需u盘和光盘安装linux

    今天折腾linux引导的时候发现一个不用任何移动介质的linux安装方法,即直接在硬盘中启动安装系统. 1.首先下载一个easyBCD.进入“添加新条目”选项选择“NeoGrub”条目,然后选择“添加 ...

  4. Mac OS X 上的安装Lisp开发环境

    到网站:https://common-lisp.net/project/lispbox/ 下载lispbox 解压下载下来的包,找到Emacs 测试: 我们也可以使用homebrew来安装lisp的解 ...

  5. poj 3281 最大流+建图

    很巧妙的思想 转自:http://www.cnblogs.com/kuangbin/archive/2012/08/21/2649850.html 本题能够想到用最大流做,那真的是太绝了.建模的方法很 ...

  6. 修改Tomcat编码方式的两种方法

    转自:http://blog.sina.com.cn/s/blog_7c76d63901018lyt.html 方法一:推荐,不会影响到其它项目  见我的另一篇博客:http://www.cnblog ...

  7. 我对java反射机制的理解

    我们平常怎么用一个使用类,怎么使用类的方法?其实就是创建一个对象,并且通过这个对象调用这个方法.不过这有一个问题,就是这个对象的载体就和这个对象产生了耦合,怎么降低两者间的耦合呢?java的反射机制就 ...

  8. node Later定时任务

    var later = require('later'); later.date.localTime(); var basic = {h: [15], m: [40], s: [0]}; var co ...

  9. 建模算法(四)——动态规划

    其实我们对着规划接触的最多最熟悉,简单来说就是一个递归问题,递归问题简单的在的地方,编程实现的难度下降了,难的地方是如何构造递归,不好的地方是资源的浪费,但是有些地方编程实现的简单的优势可以无视掉他的 ...

  10. spring实战六之使用基于java配置的Spring

    之前接触的都是基于XML配置的Spring,Spring3.0开始可以几乎不使用XML而使用纯粹的java代码来配置Spring应用.使用基于java配置的Spring的步骤如下: 1. 创建基于ja ...