ExtJS-类基本语法

更新记录

点击查看详细更新记录
2023年3月11日 根据网友[Strike.Back]反馈修复错误内容。
2022年12月3日 新增【重写已有类】节。
2022年12月2日 优化config节内容。
2022年7月2日 从笔记迁移到博客。

ExtJS教程汇总:https://www.cnblogs.com/cqpanda/p/16328016.html

ExtJS类基本语法

约定规范#

约定的作用(为什么需要约定)#

  1. 约定本质是一种限制。使用约定可以统一代码的风格,使代码更加优雅、可维护、简单。
  2. JavaScript非常灵活,解决一个问题有多种方案。

类命名约定(Class Naming Conventions)#

  1. 以大写字母开头(Uppercase Letter),后续字符使用Camel风格(Camel Case)。
  2. 类名只可以是字母或者数字。
  3. 使用.分割命名空间和类名。
  4. 顶级命名空间使用首字母大写(Pascal风格)。
  5. 次级命名空间使用首字母小写(Camel风格)。
  6. 类名首字母大写(Pascal风格)。
  7. 不要使用Ext作为应用的首级命名空间,除非是创建插件。
  8. 专用名词\缩略语不要使用全部大写。
  9. 不要使用下划线、横杠字符。
  10. 不建议使用数字。
  11. 类最好放在命名空间中,格式:(namespace).(namespace).(class)。

实例:

StudentScore
HttpHelper
Company.package.Class
Company.Class
MyCompany.util.Base64
Ext.data.JsonProxy
MyCompany.util.HtmlParser
MyCompany.server.Http

源文件约定(File Names Conventions)#

说明

  1. 类名称直接映射到存储它们的文件路径
  2. 一个文件 只能保存 一个类
  3. 源文件所在的目录 必须和 命名空间层级相同

实例

PandaApp.view.main.Main类 对应 项目文件/app/view/main/Main.js
Company.chart.axis.Numeric类 对应 /src/Company/chart/axis/Numeric.js

方法和字段约定(Method & Property & Variable Conventions)#

说明

  1. 以小写字母开头(Lowercase Letter),后续字符使用Camel风格(Camel Case)
  2. 方法和变量的名称只能包含字母和数字
  3. 方法和变量使用camel风格
  4. 不要使用下划线、横杠字符
  5. 不建议使用数字

实例

encodeUsingMd5()
getHtml()
getJsonResponse()
parseXmlContent()
getStudentScore()
updateEmployeeAge()
var isGoodName
var base64Encoder
var xmlReader
var httpServer
enableColumnResize = true

常量约定(Constant Conventions)#

说明
常量使用大写(全部大写)
实例

Ext.MessageBox.YES = "Yes"
Ext.MessageBox.NO = "No"
MyCompany.PandaModule.Math.PI = "4.13"

定义类(Defining classes)#

使用Ext.define方法

Ext.define ( className, members, [onClassCreated] ) : Ext.Base

类命名规则:AppName.folderName.ClassName
类命名实例:StudentApp.view.StudentView

参数:

className //表示类名称
members	  //键值对组成的对象,表示类的成员,比如:属性和方法
onClassCreated //可选的回调函数

当已定义的类的所有依赖项都已就绪并且类本身已完全创建时
将调用该函数回调函数

members支持的预定义关键字:

alias
alternateClassName
cachedConfig
config
extend
inheritableStatics
mixins
override
platformConfig
privates
requires
self
singleton
statics
uses
xtype (for Ext.Component only)

实例:
类文件存放位置
image
具体的类文件内容:

Ext.define('PandaApp.utl.Test',{
    doSomething: function(){
        console.log("Success~!");
    }
});

使用类
使用Ext.create方法

var test = Ext.create('PandaApp.utl.Test');
test.doSomething();

定义单例类(Defining Singleton Classes)#

  1. 单例类常用于保存配置、通用函数、预定义常量
  2. 使用singleton配置项即可,这会触发类的单例后处理器
    注意:单例类直接使用,无需创建实例,也不可以创建实例
    实例:定义一个计数器
//定义一个计数器
Ext.define('PandaApp.util.Counter', {
    extend: Ext.Base,
    singleton: true,
    config:{
        number: 0,
        step: 1
    },
    next: function(){
        this.setNumber(this.getNumber() + this.getStep());
    },
    constructor(){
        this.initConfig(); //一定要定义
    }
});

console.log(PandaApp.util.Counter.getNumber()); //0
PandaApp.util.Counter.next();
console.log(PandaApp.util.Counter.getNumber()); //1
PandaApp.util.Counter.setStep(5);
PandaApp.util.Counter.next();
console.log(PandaApp.util.Counter.getNumber()); //6

定义类的字段(Defining Property)#

//定义类型
Ext.define('PandaApp.PandaClass',{
    field1:'Panda',
    field2:666
});
//实例化类型
var obj = Ext.create('PandaApp.PandaClass');
console.log(obj.field1);
console.log(obj.field2);

注意:通常私有变量使用_下划线开头

定义类的方法(Defining Method)#

//定义类型
Ext.define('PandaApp.PandaClass',{
    field1:'Panda',
    field2:666,
    //定义方法
    doSomething: function(){
        console.log(this.field1 + ' ' + this.field2);
    }
});

//实例化类型
var obj = Ext.create('PandaApp.PandaClass');
obj.doSomething();

定义Config项(Defining Configuration)#

说明#

使用配置(Configuration)可以利用ExtJS提供的预处理机制实现属性功能。
ExtJS中使用config预处理器 来处理 类的config属性。
config属性中定义的数据会自动生成Get和Set方法(如果自己没有定义)。
注意:
自定义的类,记得在构造函数中调用initConfig方法。
如果类继承自Ext.Base,那么需要在构造函数中调用initConfig()方法。
预定义的类型已经自动调用initConfig()方法了,无需手动调用。

语法#

使用config配置项 定义 配置

//定义类型
Ext.define('PandaApp.PandaClass', {
    config: {
        property1: '',
        property2: 666
    }
});

在构造函数中调用this.initConfig(config);#

实例1:

//定义一个计数器
Ext.define('PandaApp.util.Counter', {
    extend: Ext.Base,
    singleton: true,
    config:{
        number: 0,
        step: 1
    },
    next: function(){
        this.setNumber(this.getNumber() + this.getStep());
    },
    constructor(args){
        this.initConfig(); //一定要调用

        this.callParent(args);
    }
});

console.log(PandaApp.util.Counter.getNumber()); //0
PandaApp.util.Counter.next();
console.log(PandaApp.util.Counter.getNumber()); //1
PandaApp.util.Counter.setStep(5);
PandaApp.util.Counter.next();
console.log(PandaApp.util.Counter.getNumber()); //6

实例2:

Ext.define('Student', {
    config: {
        name : 'unnamed',
        schoolName : 'Unknown'
    },
    constructor : function(config){
        this.initConfig(config);
    }
});
var newStudent = Ext.create('Student', { name: 'XYZ', schoolName: 'ABC School' });
newStudent.getName();//output: XYZ
newStudent.getSchoolName();//output: ABC School

newStudent.setName('John');
newStudent.setSchoolName('New School');

newStudent.getName();        //output: John
newStudent.getSchoolName(); //output: New School

自定义config属性的set逻辑#

自定义config属性的set逻辑,使用apply方法和update方法
apply<属性名称>方法用于:在赋值之前自定义逻辑
update<属性名称>方法用于:在赋值之后自定义逻辑

实例:apply<属性名称>方法
注意:记得要返回值,如果不返回值将不会设置属性

//定义类型
Ext.define('PandaApp.PandaClass',{
    config:{
        property1:'',
        property2:666
    },
    
    applyProperty1: function(property1){
        if(property1 == 'Panda'){
            return 'panda666.com';
        }
        else
        {
            return property1 + '.com';
        }
    }
});

//使用类型
var obj = Ext.create('PandaApp.PandaClass');
//获得属性的值
console.log(obj.getProperty1());
//给属性赋值
obj.setProperty1('Panda')
//获得属性的值
console.log(obj.getProperty1());

实例:update<属性名称>方法

Ext.define('Student',{
    config : 
    {
        name : 'unnamed',
        schoolName : 'Unknown'
    },

    constructor : function(config){
        this.initConfig(config);
    },
       
    updateName : function(newValue, oldValue){
        alert('New value: ' + newValue + ', Old value: ' + oldValue);
    }
});

var newStudent = Ext.create('Student', {name : 'xyz', schoolName : 'ABC School'});
newStudent.setName('john');

定义构造函数(Defining Constructor)#

使用constructor配置项

//定义类型
Ext.define('PandaApp.PandaClass', {
    feild1:'',
    feild2:'',
    config:{
        property1:''
    },
    constructor: function(arg1,arg2)
    {
        this.feild1 = arg1;
        this.feild2 = arg2;
        this.setProperty1(arg2);
    }
});

//使用类型
var obj = Ext.create('PandaApp.PandaClass','panda','dog');
//获得属性的值
console.log(obj.getProperty1());
//获得字段的值
console.log(obj.feild1);
console.log(obj.feild2);

调用父类构造函数

Ext.define('PandaApp.store.Customers', {
    extend: 'Ext.data.Store',  //配置继承自其他类型
    requires: [  //配置依赖项
        'myApp.model.Customer',
        'Ext.data.proxy.Ajax',
        'Ext.data.reader.Json'
    ],
    //配置构造函数
    constructor: function(cfg) {
        var me = this; //获得当前对象的引用
        //检测参数是否为空,为空则进行设置空对象
        cfg = cfg || {};
        //调用父类构造函数
        me.callParent([Ext.apply({
            //预设配置项
        }, cfg)]);
    }
});

定义静态成员(Defining Static Member)#

使用statics配置项#

使用statics配置项即可定义类的静态成员
在类的内部使用 this.statics().静态成员 或者 this.self.静态成员 访问静态成员
在类的外部使用 类名称.静态成员 即可访问静态成员
注意:this.self在类内部表示引用类自身
注意:默认情况下,静态成员不被子类继承,需被子类继承可以使用inheritableStatics

Ext.define('PandaApp.Direction',{
    statics:{
        UP:1,  //静态属性
        DOWN:2,
        LEFT:3,
        RIGHT:4,
        sayHello: function(name){ //静态方法
            console.log(name + ' Hello!');
        }
    },
    doSomething: function(){
        //在类的内部使用静态成员
        console.log(this.statics().UP); //1
    }
});

//在类外部使用静态字段
console.log(PandaApp.Direction.UP);   //1
console.log(PandaApp.Direction.DOWN); //2
console.log(PandaApp.Direction.LEFT); //3
console.log(PandaApp.Direction.RIGHT);//4
//在类外部使用静态方法
PandaApp.Direction.sayHello('Panda');

//实例化类
var obj = Ext.create('PandaApp.Direction');
obj.doSomething();

在实例方法中调用静态成员

Ext.define('PandaApp.TestClass',{
    statics: {
        //静态方法
        SAYHELLO: function () {
            console.log('Panda666');
        },
        //静态字段
        PANDA:1,
    },

    //实例方法
    method1: function () {
        //在实例方法中调用静态方法
        this.statics().SAYHELLO();
        //在实例方法中调用静态字段
        console.log(this.self.PANDA);
    }
});

let testClass = Ext.create('PandaApp.TestClass');

定义可以被继承的静态成员#

//定义父类
Ext.define('PandaApp.config.KeyValuePair',{
    inheritableStatics: {
        DEVELOPMENT:true
    }
});

//定义子类
Ext.define('PandaApp.config.KeyValuePairForModule',{
    extend: 'PandaApp.config.KeyValuePair',
})

//测试
console.log(PandaApp.config.KeyValuePairForModule.DEVELOPMENT);

定义继承(Defining Inheritance)#

使用extend配置项

//定义类型
Ext.define('PandaApp.PandaClass',{
    extend:'Ext.tab.Panel'
});

//实例化类型
var obj = Ext.create('PandaApp.PandaClass');
console.log(obj.getId());

调用父类的构造函数
使用callParent方法

//定义Person类
Ext.define('Person',{
    _name: 'unknown',
    constructor: function(name){
        this._name = name;
    },

    getName: function(){
        console.log("My Name is " + this._name);
    }
});

//定义Student类
Ext.define('Student', 
{
    extend : 'Person',
    _schoolName : 'Unknown',

    constructor : function(name, schoolName){
        this._schoolName = schoolName || 'Unknown';
    
        //调用父类构造函数
        this.callParent(arguments);
    },
    
    getSchoolName : function(){
        console.log("My school name is " + this._schoolName);
    }
});

//使用
var panda = Ext.create('Student','Panda666','PandaSchool');
panda.getName();
panda.getSchoolName();

定义混入(Defining Mixins)#

说明#

使用混入(mixins)可以方便的复用另一个类的已经定义好的成员

语法#

使用mixins配置项即可,支持 数组形式 和 对象形式

使用数组格式直接引入另一个类的全部成员

//定义工具类型
Ext.define('PandaApp.Util.SayHello',{
    sayHello: function(){
        console.log('Say Hello!');
    }
});
Ext.define('PandaApp.Util.SayGood',{
    sayGood: function(){
        console.log('Say Good!');
    },
    sayGood2: function(name){
        console.log(name + ' Good!')
    }
});

//定义具体类
Ext.define('PandaApp.pandaModule.controller.SomeController',{
    xtype: 'panda',
    mixins : [ //将工具类混入
        'PandaApp.Util.SayHello',
        'PandaApp.Util.SayGood'
    ]
});

//实例化类型
var panda = Ext.create('PandaApp.pandaModule.controller.SomeController');
//测试类型
panda.sayHello(); //Say Hello!
panda.sayGood();  //Say Good!
panda.sayGood2('Panda'); //Panda Good!

使用对象格式引入
//定义工具类型
Ext.define('PandaApp.Util.SaySomething',{
    sayHello: function(){
        console.log('Say Hello!');
    },
    sayGood: function(){
        console.log('Say Good!');
    }
});

//定义具体类
Ext.define('PandaApp.pandaModule.controller.SomeController',{
    xtype: 'panda',
    mixins : { //将工具类混入
        say: 'PandaApp.Util.SaySomething'
    }
});

//实例化类型
var panda = Ext.create('PandaApp.pandaModule.controller.SomeController');
//测试类型
panda.sayHello(); //Say Hello!
panda.sayGood();  //Say Good!

使用mixinConfig#

使用mixinConfig配置项可以使被混入时
提供一个before和after的钩子(hooks),分别在方法之前和之后执行
注意:被混入项需要继承自Ext.Mixin

实例:

//定义被混入的类型
Ext.define('PandaApp.utl.SaySomthing',{
    extend: 'Ext.Mixin',
    mixinConfig: {  //定义混入钩子
        before: {  //在sayHello之前执行sayBefore函数
            sayHello: 'sayBefore'
        },
        after: {   //在sayHello之后执行sayAfter函数
            sayHello: 'sayAfter'
        }
    },
    sayBefore: function(){
        console.log('This Is Before Action!');
    },
    sayAfter: function(){
        console.log('This Is After Action!');
    }
});

//定义类型
Ext.define('PandaApp.controller.SomeController', {
    mixins: [
        'PandaApp.utl.SaySomthing',
    ],
    sayHello: function(){
        console.log('Say Hello!');
    }
});

//定义实例进行测试
var obj = Ext.create('PandaApp.controller.SomeController');
obj.sayHello(); 
//将会显示三句话
//This Is Before Action!
//Say Hello!
//This Is After Action!

代替基类中的方法(Override Base’s Method)#

使用override配置项

Ext.define('My.ux.field.Text', {
    override: 'Ext.form.field.Text',
    setValue: function(val) {
        this.callParent(['In override']);
        return this;
    }
});

重写已有类#

Ext.override(Object originalCls, Object overrides) 

或者

PandaApp.PandaClass.override({
  //New members...
});

实例:

Ext.define('PandaApp.PandaClass', {
    welcome: function() {
        console.log('Panda Test');
    }
});

Ext.override('PandaApp.PandaClass', {
    goodBye: function() {
        console.log('Goodbye');
    },

    runAll: function() {
        this.welcome();
        this.goodBye();
    }
});

var pandaClass = new PandaApp.PandaClass();
pandaClass.runAll();  // Welcome to the app
               // Goodbye

定义类的别名(Defining Class Alias)#

使用alias配置项即可定义类别名
提示:按照命名约定别名应使用全部小写的风格
别名在使用xtype时非常有用

在类别名中使用前缀,可以定义不同类型的别名,常用前缀:

controller		用于定义视图控制器(view controller)
view			用于视图(view)
model			用于模型(model)
viewmodel		用于视图模型(viwmodel)
store			用于数据仓库(Ext.data.Store)
feature			用于网格(Grid features)
plugin			用于插件(plugins)
widget			用于组件(components)
data.field		用于自定义字段
layout.xx		用于布局

注意:都是小写,没有大写

实例1:定义控制器别名,使用controller前缀

Ext.define('PandaApp.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.main'  //定义控制器别名
});

实例2:定义组件别名,使用widget前缀,可以当做xtype使用

//定义类型
Ext.define('PandaApp.PandaPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.pandaPanel'  //定义组件别名
});

//创建类型实例(自定义类型)
Ext.create('widget.pandaPanel');
//创建类型实例(预定义类型)
Ext.create('widget.panel');
//创建类型实例(预定义类型)(直接使用别名)
Ext.create({
    xtype:'panel',
    title: 'PandaTtile',
    renderTo:Ext.getBody()
});

定义类依赖项#

使用requires配置项
实例:

Ext.define('PandaApp.some.SomeClass', {
    requires: [   //定义依赖
        'PandaApp.Some.SomeOtherClass1',
        'PandaApp.Some.SomeOtherClass2',
    ],
    //...
});

创建类的实例(create Instance)#

使用Ext.create()方法

Ext.create ( [name], [args] ) : Object 

name支持:
完整的类型名称(带命名空间)
类别名(widget.别名)

xtype
xclass

实例1:使用完整的类型名称

//定义类型
Ext.define('PandaApp.PandaClass',{
    constructor:function(arg1,arg2)
    {
        //do something
    }
});

//使用类型
var obj = Ext.create('PandaApp.PandaClass','panda','dog');

实例2:使用类型别名

//定义类型
Ext.define('PandaApp.PandaPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.pandaPanel'  //定义组件别名
});

//创建类型实例(自定义类型)
Ext.create('widget.pandaPanel');
//创建类型实例(预定义类型)
Ext.create('widget.panel');

实例3:使用xtype

//定义类型
Ext.define('PandaApp.PandaPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.pandaPanel'  //定义组件别名
});

//创建类型实例(预定义类型)(直接使用别名)
Ext.create({
    xtype:'panel',
    title: 'PandaTtile',
    renderTo:Ext.getBody()
});

实例4:使用xclass

var window = Ext.create({
    xclass: 'Ext.window.Window', // any valid value for 'name' (above)
    width: 600,
    height: 800,
    //...
});

实例5:三种方式汇总

//定义类型
Ext.define('PandaApp.PandaPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.pandaPanel'  //定义组件别名
});

//创建类型实例(使用完整的类型名称)
Ext.create('Ext.panel.Panel',{});
//创建类型实例(自定义类型)
Ext.create('widget.pandaPanel');
//创建类型实例(预定义类型)
Ext.create('widget.panel');
//创建类型实例(预定义类型)(直接使用别名)
Ext.create({
    xtype:'panel',
    title: 'PandaTtile',
    renderTo:Ext.getBody()
});

使用类实例#

//构建类
Ext.define('Panda.Test1.Person',{
        name:'someone',
        constructor: function(name){
            this.name = name;
        },
        who: function(){
            console.log('this is ' + this.name);
        }
    }
);

//实例化类
var panda = Ext.create('Panda.Test1.Person','Panda');
//使用类
panda.who();

错误处理和调试#

抛出错误,使用throw,在浏览器调试窗口中可以看到错误信息和调用栈信息

//定义类型
Ext.define('PandaApp.PandaClass',{
    doSomething:function(){
        //抛出错误
        throw new Error('This is Panda Throw');
    }
});

//使用类型
var obj = Ext.create('PandaApp.PandaClass');
obj.doSomething();

获得方法的名称,使用Ext. getDisplayName()方法

//定义类型
Ext.define('PandaApp.PandaClass',{
    doSomething:function(){
        //抛出错误
        throw new Error('This is Panda Throw ' + Ext.getDisplayName(arguments.callee));
    }
});

//使用类型
var obj = Ext.create('PandaApp.PandaClass');
obj.doSomething();

ExtJS类常用配置项#

requires: 		自定义类型需要引用其他类时,意味着依赖其他类
			就可以使用该配置项引入依赖项
			该配置项类似于C#中的using
			主要作用是让ExtJS在实例化类时
			先去加载requires中的类
extend:		在自定义类时,用来指定自定义类扩展/继承的类
items:			用来定义当前组件(Component)的子组件
xtype:			用来声明当前配置对象使用的类型
			可以在API文档的类名旁边查看到类型对应的xtype
			或者用来指定自定义类型的xtype值
mixins:		将一个类混入到定义的类
			本质是将混入类的方法复制到要定义的类的原型中
config:		类似C#中的属性
			在config中定义的数据将自动创建修改(Set)和查询(Get)方法
id:			为组件定义唯一的标识符,方便查找组件
			也作为HTML标签的id
itemId:		作用与id类似,不过不作为HTML代码的标识符
			标识符的作用域仅定义在容器内
scope:			用来定义作用域
defaults:		简化组件的定义,当父组件使用了defaults配置项
			在创建子组件时,会将该配置项中定义的配置应用到子组件中
defaultType:		与defaults作用类似,不过是用来设置子组件类型,即子组件的xtype
layout:		用来指定容器的布局
reference:		为组件指定引用名称
			以便在ViewController中使用lookupReference方法获得该组件
bind:		 	为组件设置绑定,绑定值可以是配置对象,可以是字符串
			当值为配置对象时,配置对象的属性为组件的属性,其值为组件属性值
			当值为字符串时,会使用组件defaultBindProperty属性指定属性作为绑定
refs:			在视图中定义refs用于设置UI组件与Controller的关系
			比如:在视图文件中定义
			refs: {
				loginButton: '#Somebutton',
				somePanel: '#somePanel'
			}
				然后在对应的Controller文件中可以直接使用getLoginButton()访问
control:		为组件定义事件关联
           		直接使用选择器选择组件或者refs中已定义的组件
			比如:
			control: {
				'#Somebutton': {  //直接使用选择器
					tap: 'onLogin',
				},
				loginButton: {   //注意:loginButton必须在refs中已定义好
					tap: 'onLogin',
				}
			}

作者:重庆熊猫

出处:https://www.cnblogs.com/cqpanda/p/16404064.html

版权:本作品采用「不论是否商业使用都不允许转载,否则按3元1字进行收取费用」许可协议进行许可。

posted @   重庆熊猫  阅读(1829)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示