組件的構造函數中一般都可以包含一個對象,這個對象包含創建組件所需要的配置屬性及值,組件根據構造函數中的參數屬性值來初始化組件。比如下面的例子:
<script>
var obj={title:"hello",width:300,height:200,html:'<h1>Hello,easyjf open source</h1>'};
var panel=new Ext.Panel(obj);
panel.render("hello");
</script>
<div id="hello"> </div>
運行上面的代碼可以實現如下圖所示的結果:
可以省掉變量obj,直接寫成如下的形式:
var panel=new Ext.Panel({title:"hello",width:300,height:200,html:'<h1>Hello,easyjf open source</h1>'});
panel.render("hello");
render方法后面的參數表示頁面上的div元素id,也可以直接在參數中通過renderTo參數來省略手動讞用render方法,只需要在構造函數的參數中添加一個renderTo屬性即可,如下:
new Ext.Panel({renderTo:"hello",title:"hello",width:300,height:200,html:'<h1>Hello,easyjf open source</h1>'});
對于容器中的子元素組件,都支持延遲加載的方式創建控件,此時可以直接通過在需要父組件的構造函數中,通過給屬性items傳遞數組方式實現構造。如下面的代碼:
var panel=new Ext.TabPanel({width:300,height:200,items:[
{title:"面板1",height:30},{title:"面板2",height:30},{title:"面板3",height:30}]
});
panel.render("hello");
注意中括號中加粗部份的代碼,這些代碼定義了TabPanel這個容器控件中的子元素,這里包括三個面板。上面的代碼與下面的代碼等價:
var panel=new Ext.TabPanel({width:300,height:200,items:[new Ext.Panel(
{title:"面板1",height:30}),new Ext.Panel({title:"面板2",height:30}),new Ext.Panel({title:"面板3",height:30})]
});
panel.render("hello");
前者不但省略掉了new Ext.Panel這個構造函數,最重要前者只有在初始化TabPanel的時候,才會創建子面板,而第二種方式則在程序一開始就會創建子面板。也就是說,前者實現的延遲加載。
轉載:EasyJF開源的冷雨