ExtJS笔记2 Class System

时间:2015-02-02 00:32:40   收藏:0   阅读:341

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:

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:

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:

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

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风格。

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:

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

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

4) Properties

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);

 

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实现类创建之前的预处理。包含的特性有:

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.

技术分享

 

技术分享

 

See Also

原文:http://www.cnblogs.com/jimcheng/p/4266576.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!