ExtJS 4 类的定义

类的定义与类方法的调用


// Define new class 'Vehicle' under the 'Cookbook' namespace
Ext.define('Cookbook.Vehicle', {
    // class configuration goes here
    Manufacturer : 'Aston Martin',
    Model : 'Vanquish',

    getDetails : function() {
        alert('I am an ' + this.Manufacturer + ' ' + this.Model);
    }
}, function(){
    Console.log('Cookbook.Vehicle class defined!');
});

var myVehicle = Ext.create('Cookbook.Vehicle');
alert(myVehicle.Manufacturer);
myVeicle.getDetails();

说明

  • 第二行,使用Ext.define定义了一个Cookbook.Vehicle类,Cookbook是命名空间。
  • 第四行、第五行,加入了两个属性。
  • 第七行,加入了一个getDetails方法。
  • 第十行,加入了callback方法,这个方法将在类定义之后执行。
// Define new class 'Vehicle' under the 'Cookbook' namespace
Ext.define('Cokbook.Vehicle', {
    config : {
        // class configuration goes here
        Manufacturer : 'Aston Martin',
        Model : 'Vanquish',
    },

    constructor : function(config) {
        // initialise our config object
        this.initConfig(config);
    },

    getDetails : function() {
        alert('I am an ' + this.Manufacturer + ' ' + this.Model);
    }
}, function() {
    Console.log('Cookbook.Vehicle class defined!');
});

// create a new instance of Vehicle class
var myVehicle = Ext.create('Cokbook.Vehicle');
// display its details
myVeicle.getDetails();
// update Vehicle details
vehicle.setManufacturer('Volkswagen');
vehicle.setModel('Golf');
// display its new details
vehicle.getDetails();

 

说明

  • 如果在类的定义内,使用config标明配置属性,则Ext会自动生成属性相关的set、get、apply方法。
Ext.define('Cookbook.Vehicle', {
    Manufacturer : 'Aston Martin',
    Model : 'Vanquish',

    getManufacturer : function() {
        return this.Manufacturer;
    },
    setManufacturer : function() {
        this.Manufacturer = value;
    },
    resetManufacturer : function() {
        this.setManufacturer('Aston Martin');
    },
    applyManufacturer : function(manufacturer) {
        // perform some action to apply the value(e.g. update a DOM element
        return manufacturer;
    },
    getModel : function() {
        return this.Model;
    },
    setModel : function(value) {
        this.Model = value;
    },
    resetModel : function() {
        this.setModel('Vanquish');
    },
    applyModel : function(model) {
        // perform some action to apply the value (e.g. update a DOM element)
        return model;
    },
    getDetails : function() {
        alert(' ... ')
    }
});

总结


  1. 使用Ext.define()方法定义类主要有三个部分:类配置部分,类方法,定义回调方法。
  2. ExtJS中,定义、实例化一个类时,直接使用字符串的命名的形式。

相关文章: