作者:Dflying Chen (http://dflying.cnblogs.com/ )
很多時候我們需要在頁面載入以後立刻調用一些Web Service,比如一個用戶端的Atlas ListView會在載入後立刻得到初始化的填充資料。雖然這可以使用Atlas的InitialData控制項完成,但對於其它的一些要求,比如在頁面載入後立刻執行一段Atlas指令碼(其中用到了Atlas對JavaScript的擴充),我們仍需要一個頁面載入的事件來觸發這些操作。
很多朋友採用如下的兩種方法:
- 直接在頁面的Script段中書寫要執行的指令碼。
- 在頁面的onload JavaScript事件處理方法中書寫。
這些都是不正確的方式,會有錯誤發生,原因很簡單:Atlas的用戶端實現也是一段JavaScript,需要先執行一次才可以工作,而上述兩種方法的語句都是在Atlas用戶端實現被初始化前啟動並執行,自然會導致錯誤。
Atlas充分意識到了這個需求,提供了Framework內部的OnLoad事件,該事件將在Atlas Framework初始化以後被引發。想捕獲這個事件,您需要在頁面的Atlas XML Script中聲明:
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<application id="application" load="OnApplicationLoad" />
</components>
</page>
其中application作為當前啟動並執行Atlas程式的引用,提供了一個load事件,這樣我們通過指定它的事件處理函數,即可在Atlas Framework初始化之後執行我們的代碼。
下面來看一個例子,Web Service如下,還是簡單的兩個數相加:
[WebMethod]
public int AddInt(int int1, int int2)
{
return int1 + int2;
}
然後ASPX頁面中添加ScriptManager並對上述Web Service進行引用:
<atlas:ScriptManager ID="scriptManager" runat="server" EnableScriptComponents="true">
<Services>
<atlas:ServiceReference Path="SimpleWebService.asmx" />
</Services>
</atlas:ScriptManager>
頁面上再添加兩個input用來提供兩個加數:
<input id="value1" type="text" value="1" />
<input id="value2" type="text" value="2" />
加上捕獲Atlas Framework load事件的XML Script定義:
<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<application id="application" load="OnApplicationLoad" />
</components>
</page>
</script>
下面是事件處理函數以及相應的Callback,可以看到我們應用了三種Atlas Framework提供的擴充:
- $()方法,等同於document.getElementById()
- Sys.UI.TextBox類,封裝了HTML的input元素
- 對Web Service調用的Mashup
function OnApplicationLoad()
{
var value1 = new Sys.UI.TextBox($('value1'));
var value2 = new Sys.UI.TextBox($('value2'));
Dflying.SimpleWebService.AddInt(
value1.get_text(),
value2.get_text(),
OnComplete
);
return false;
}
function OnComplete(result)
{
alert(result);
}
運行結果,沒有任何問題:
本執行個體的原始碼可以在此下載:http://files.cnblogs.com/dflying/ApplicationLoadEventDemo.zip