http://hi.baidu.com/commondcn/item/9c46ef262d5c79122b0f1ce3
DOJO Widget 詳解
Dojo中對widget進行擴展存在兩種形式
1) dojo.declare("inheritTest.myClass",[dijit._Widget, dijit._Templated],
這意味着你的widet繼承自dojo widget的兩個基類:dijit._Widget, dijit._Templated。
其中,在dijit._Widget類中存在六個方法,分別爲:
l postscript
l create
l postMixInProperties
l buildRendering
l postCreate
l startup
來看一下默認的postscript方法
postscript: function(params, srcNodeRef){
this.create(params, srcNodeRef);
},
其中接收兩個參數,回憶一下dojo提供的dijit組件的一般創建方法,例如:new dijit.form.FilteringSelect({store:myStore, label:’test’},dom);實際上,這兩個參數即對應了postscript的兩個參數,第一個是傳入相關的屬性,第二個是設定此widget被加載的dom節點。即我們通過在js中 new 或者在html中使用標籤<div dojoType= inheritTest.myClass/>的方式加載widget時,第一步將調用postscript方法,而postscript方法將調用create方法。Create方法實際上執行了創建這個widget的流程。在此方法中包含了postMixInProperties,buildRendering,postCreate方法postMixInProperties在所有Properties被賦值以後調用,在此函數調用前我們可以看到執行如下語句:
if(params)
{
dojo.mixin(this,params);
}
將params傳入的屬性和widget原有的屬性mixin.
接下來buildRendering()函數是處理template用的將templateString或者templatePath所定義的<DIV>的內容渲染到頁面上。如果其中定義到了其他的widget將調用其的create將其生成。
在create函數執行的末端將調用postCreate函數,做生成widget後的一些處理。
Startup將在create執行完畢以後調用。
下面具體的看一下執行的流程:
建立一個base類:
dojo.declare("inheritTest.baseClass", [dijit._Widget, dijit._Templated],
{
widgetsInTemplate: true,
constructor:function(){
console.debug('base_constructor');
},
postMixInProperties:function(){
console.debug('base_postMixInProperties');
},
buildRendering:function(){
console.debug('base_buildRendering');
},
postCreate: function(){
console.debug('base_postCreate');
},
startup: function(){
console.debug('base_startup');
}
});
}
再建立一個child類:
dojo.declare("inheritTest.childClass",[dijit._Widget, dijit._Templated],
{
widgetsInTemplate: true,
templatePath :'inheritTest/template/childTemplate.html',
constructor:function(){
console.debug('child_constructor');
},
postMixInProperties:function(){
console.debug('child_postMixInProperties');
},
buildRendering:function(){
console.debug('child_buildRendering');
this.inherited(arguments);
},
postCreate: function(){
console.debug('child_postCreate');
},
startup: function(){
console.debug('child_startup');
}
});
}
在inheritTest.childClass的模板中我們調用了baseClass:<div><div dojoType=inheritTest.baseClass></div></div>
建立一個test.html內容如下:
<body class="tundra">
<div dojoType="inheritTest.childClass" ></div>
</body>
執行程序,console輸出如下:
2) dojo.declare("inheritTest.childClass",inheritTest.baseClass,{});
這採用了傳統的繼承方式,這種方式能夠使用基類的所有方法和屬性,但是除了構造函數以外,如果希望覆寫基類的方法時執行基類的方法,則需要在覆寫類中加入語句:this.inherited(arguments);