ExtJS 组件的扩展和继承
ExtJS 的组件很丰富,可有时候还是满足不了需求,需要扩展 ExtJS 的组件实现自制组件。
扩展组件的时候,最好给其设置单独的 xtype, 这样就能比较容易的和其他组件集成。
虽说扩展 ExtJS 的组件只不过是用 Ext.extend() 来实现,多少还是有些窍门。
例: 扩展 Ext.Panel,得到名为 MyComponent 的组件。 xtype 设置为 mycomponent。
MyComponent = Ext.extend(Ext.Panel, {
initComponent: function(){
Ext.apply(this, {
_name: 'MyComponent' // 非必须,调试时用 console.log 等可显示对象名。
});
this.items = [{
// 如有固定的 items,须在此设定
}];
MyComponent.superclass.initComponent.call(this);
}
});
// 注册 xtype, 此后、只需指定属性 xtype: 'mycomponent' 即可实现组件的延迟渲染。
Ext.reg('mycomponent', MyComponent);
代码解释:
1.initComponent 函数
组件初始化时执行的函数。不过,这和 new 的时候所执行的 Contructor 有所不同。实际上,从 Component 的 Contructor 到 initComponent 的执行,有一个过程。一些有影响的参数,须在 initComponnt 中设定。
- 有关 Layout 的设置,必须在 initComponent 中实行。
- collapsible 须通过对象属性来设定。如:
items:[{
xtype: 'mycomponent',
collapsible: true
}]
2.Ext.reg
调用方法: Ext.reg(xtype字符串, 对象) 。在任意组件中、加入以上 MyComponent 的时候、用 xtype 的方法指定,就能实现迟延渲染。
3.initComponent 内部的 this,是以上 MyComponent 的接口。
4.new MyComponent(config) 生成实例之后、initComponent 内部的 this 通过 apply 追加了属性。
5.Ext.apply(object1,object2)
这是把 object2 合并到 object1。通过这个函数,object2 所持有的属性和方法,全被追加到object1。 同名属性将会被 object2 的属性所覆盖。