混入(Mixins)
Mixins特性在Ext JS 4的版本引入,该特性允许我们在不使用继承的前提下,调用另一个类的方法。Mixins特性使用mixins这个关键词定义,其值是一个JSON格式的对象。该对象里,key是方法名,value是方法所在类。看下面这个例子:
Ext.define('Person', {
name: 'Unknown',
constructor: function(name) {
if (name) {
this.name = name;
}
},
getName: function() {
alert("My name is " + this.name);
},
eat: function(foodType) {
alert("I'm eating " + foodType);
}
});
Ext.define('Student', {
schoolName: '',
constructor: function(schoolName) {
this.schoolName = schoolName || 'Unknown'
},
mixins: {
eat: 'Person'
},
getSchoolName: function() {
alert("I am a student of " + this.schoolName);
}
});
var studentObj = new Ext.create('Student', 'XYZ');
studentObj.eat('Sandwich');
在上面的那个例子中,Student类定义了一个mixins,并指定’eat’作为property,’Person’作为方法定义的类。现在就能像这样:studentObj.eat(),直接调用方法了(实际上,这个方法定义在了Person类中)。
类似于Java中,在一个类中定义另一个类的对象作为成员变量。
配置选项(Config)
Ext JS拥有配置项(Config)的特性。 配置项可以定义有默认值的、同其它类成员完全隔离的、公共属性。这些属性将被其他类成员完全封装。 配置项所声明的属性默认有getter和setter方法。定义的时候,config关键词作为key,JSON对象作为value,看一下这个例子:
Ext.define('Student', {
config :
{
name : 'unnamed',
schoolName : 'Unknown'
},
constructor : function(config){
this.initConfig(config);
}
});
上面的例子里,通过构造函数来初始化配置项。同JavaBean一样,配置项的getter和setter方法的命名方法也是:getXxxx()和setXxxx(),看一下下面的使用的例子,我们并未显式地定义getter和setter:
//这里的构造函数初始化了配置项。
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
注意:我们不能直接使用点号访问符来为配置项里的属性设置值了:
newStudent.name = 'Steve'; //Not valid.
newStudent.setName('Steve');//Valid
getter和setter方法是隐藏的,当有新的需求,就需要为setter方法追加自定义的逻辑了。Ext JS提供了两个自定义的setter方法分别是:apply和update。
apply() | update() | |
---|---|---|
作用时刻 | 配置项属性赋值前 | 配置项属性赋值后 |
命名规则 | 大驼峰(CamelCase) | 大驼峰(CamelCase) |
同时存在优先 | ✔ |
看一下下面的例子:
Ext.define('Student', {
config :
{
name : 'unnamed'
},
constructor : function(config){
this.initConfig(config);
},
applyName: function(name){
console.log('applyName: ' + name);
return Ext.String.capitalize(name);
},
updateName: function(newVal, oldVal){
console.log('New Value: ' + newVal + ', Old Value: ' + oldVal);
}
});
var newStudent = Ext.create('Student');
//applyName: unnamed
?_dc=1502808091028:23 New Value: Unnamed, Old Value: undefined
console.log(newStudent.getName());
newStudent.setName('steve');
console.log(newStudent.getName());//output: Steve
newStudent.setName('Dive');
console.log(newStudent.getName());
运行结果,六个console.log()的结果,能够很清晰的说明问题了: