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);}}
加了上述代碼之後,可以控制底部和底部地區的顯示與隱藏。