跟我一起学extjs5(07--继承自定义一个控件)

来源:互联网 发布:淘宝月老祠堂 假货 编辑:程序博客网 时间:2024/04/29 22:16


跟我一起学extjs5(07--继承自定义一个控件)


        Extjs的开发都可以遵循OOP的原则,其对类的封装也很完善了。自定义一个控件最简单的办法就是继承一个已有的控件。根据上一节的需要,我做了一个Button的子类。首先根据目录结构,在app目录下建立一个ux目录,将自定义控件都放在这个目录下。在ux目录下建立一个文件ButtonTransparent.js。
/** * 定义了一个背景透明的Button类,继承于Button */Ext.define('app.ux.ButtonTransparent', {extend : 'Ext.button.Button', // 继续于Ext.button.Buttonalias : 'widget.buttontransparent', // 此类的xtype类型为buttontransparent// 类初始化时执行initComponent : function() {// 设置事件监听this.listeners = {// 鼠标移开,背景设置透明mouseout : function() {this.setTransparent(document.getElementById(this.id));},// 鼠标移过,背景取消透明mouseover : function() {var b = document.getElementById(this.id);b.style.backgroundImage = '';b.style.backgroundColor = '';b.style.borderColor = '';},// 背景设置透明afterrender : function() {this.setTransparent(document.getElementById(this.id));}};this.callParent(arguments); // 调用你模块的initComponent函数},setTransparent : function(b) {b.style.backgroundImage = 'inherit';b.style.backgroundColor = 'inherit';b.style.borderColor = 'transparent';}});

        这个类继续于Button,只加入了3个事件,当鼠标移到此控件上的时候显示背景,鼠标移开过后背景设置为透明。afterrender事件表示在此控件渲染后执行透明。此控件完成之后,需要在Top和Button中引入此文件,并且设置items中控件的默认xtype为buttontransparent。
        在Top.js中加入以下几条语句:
uses : ['app.ux.ButtonTransparent'],defaults : {xtype : 'buttontransparent'},
        uses引入该控件,defaults属性将会把xtype的值赋给items中创建的类中(如果没有指定xtype)。这样下面的代码都不用改,所有的原来是button的类,都会被指定为ButtonTransparent类。Button.js中同样加入这二个属性值即可。
        现在的界面如下:

        
        
        下面完成另外一个功能,可以隐藏和显示顶部区域和底部区域。
        在底部区域的最后一个位置加一个按钮,按下之后,将隐藏顶部和底部区域,同时在最右上角显示一个可以显示顶部和底部的控件。
        在Top.js的items的最后部分加上一个按钮,指定handler事件
{glyph : 0xf102,handler : 'hiddenTopBottom',tooltip : '隐藏顶部和底部区域'}

        在MainController.js中加入二个函数:
// 隐藏顶部和底部的按钮事件hiddenTopBottom : function() {// 如果要操纵控件,最好的办法是根据相对路径来找到该控件,用down或up最好,尽量少用getCmp()函数。this.getView().down('maintop').hide();this.getView().down('mainbottom').hide();if (!this.showButton) { // 显示顶部和底部的一个控件,在顶部和底部隐藏了以后,显示在页面的最右上角this.showButton = Ext.widget('component', {glyph : 0xf013,view : this.getView(),floating : true,x : document.body.clientWidth - 32,y : 0,height : 4,width : 26,style : 'background-color:#cde6c7',listeners : {el : {click : function(el) {var c = Ext.getCmp(el.target.id); // 取得component的id值c.view.down('maintop').show();c.view.down('mainbottom').show();c.hide();}}}})};this.showButton.show();},// 如果窗口的大小改变了,并且顶部和底部都隐藏了,就要调整显示顶和底的那个控件的位置onMainResize : function() {if (this.showButton && !this.showButton.hidden) {this.showButton.setX(document.body.clientWidth - 32);}}

      加了上述代码之后,可以控制底部和底部区域的显示与隐藏。


15 0