您的位置:知识库 » .NET技术

深度解析ASP.NET中的Callback机制

作者: Teddy's Knowledge Base  来源: 博客园  发布时间: 2010-08-08 20:46  阅读: 4215 次  推荐: 0   原文链接   [收藏]  
[1] 深度解析ASP.NET中的Callback机制
[2] 深度解析ASP.NET中的Callback机制

  看到不少朋友最近在写使用callback的文章,也有点手痒,也来涂鸦一下,挖掘挖掘callback的潜力。callback的一般使用方法还算简单,直接参照msdn的帮助和范例就足够了。但是想要真正用好、用精,或者想开发一些基于callback机制的WEB组件,那么,就要先深入了解callback的实现机制了。在本文中,Teddy将和您一起解析callback的整个调用、反馈机制,相信对于帮助您更好的使用callback,将能有一定的益处。
  Callback vs ASP.NET AJAX
  首先,谈谈ASP.NET AJAX。很多朋友可能会觉得奇怪,已经有了Callback,为什么又要出ASP.NET AJAX呢?关于这个问题,ASP.NET AJAX的作者怎么解释,我倒没有去调查。只不过从我个人对callback和ASP.NET AJAX的使用感受来讲,觉得,callback作为一个接口和postback非常类似的实现,肯定是为了让用户类似使用postback来使用它。但是,它的这个类似postback的机制,应该说使用上还不是特别方便,也不易扩展,当然这是相比于其他的AJAX框架实现来说的。因此,微软方面借鉴了许多的已有的AJAX实现,如Prototype,Backbase以及AJAX.NET,并结合ASP.NET2.0的部分特有功能,发明了这样一个博采众长的AJAX框架。基于ASP.NET AJAX来开发AJAX应用有多好,很难量化的来说,但至少不比其他的这些AJAX框架来的差是肯定的,加上微软这个后台,以及像live.com这样的重量级站点的应用推广,其影响当然是值得期待的。
  不过,这也不是说callback实现没一无是处了,作为程序员,我们需要有正确的态度,在正确的使用情形,使用最正确的技术。没有哪一个框架是万能的,是适合任何使用环境的;就像大家都在争论那个软件开发方法最好,CMMi,RUP,XP,AGILE~~,其实,没有最好,最合适的才是最好的。我们最应该做的,是了解各种方案的原理和优缺点,从而,合理的使用正确的工具来解决实际问题。
  Begin from Client Script
  我们都知道,凡是AJAX,从底层来讲,无外乎两种实现机制:XMLHTTP以及IFRAME。在AJAX这个词获得广泛关注之前,其实,基于这两种底层实现的功能框架,或者基于这两种技术的无刷新效果实现就已经被广泛的使用了。当然,发展到今天,在使用接口方面,这些底层机制的细节往往被框架给隐藏了,使用接口变得越来越简单,用户只要调用这些简单接口,没有必要知道具体是怎么实现效果的了。
  不过,这里我们既然是要解析callback的实现机制,那还是让我们从一个callback调用的客户端脚本调用开始,看看,微软是怎么实现这个callback机制的。
  1、ClientScript.GetCallbackEventReference(...)
  要激发一个callback,首先,当然需要在客户端本中发出一个调用。一个典型的调用语法如下:

<script language="javascript" type="text/javascript">
function any_script_function(arg, context)
{
<%= ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context")%>;
}
</script>

  ClientScript.GetCallbackEventReference(...)将根据传入的参数返回实际的回调脚本。这个函数有多个重载版本,因此,这些参数的含义,大家可以参考MSDN。以具体的上面这段示例代码中的参数来说:
  - this表示执行回调的的服务端控件是当前这个Page,当前的Page必须实现ICallbackEventHandler接口,包括必须实现string GetCallbackResult()和void RaiseCallbackEvent(eventArgument)这两个接口函数,这个参数也可以是指向某个WEB控件的引用,当然,这个空间也必须实现ICallbackEventHandler接口;
  - "arg"是将被传给RaiseCallbackEvent的参数eventArgument的值,可以使人以自定义格式的字符串;
  - "ReceiveServerData"是当回调成功之后,处理返回内容的客户端脚本函数的名称,这个函数必须存在于执行回调的页面,并且这个函数可以包含两个参数,例如:

<script type="text/javascript">
function ReceiveServerData(result, context)
{

}
</script>

  这两个参数,分别是回调的返回数据result,和原封不动被返回的我们激发回调时的这个context参数,当然,这两个参数都是字符串类型的。
  - "context"就不用多解释了,记得这个参数会被原封不动的传给指定的返回数据处理函数就行了。MSDN的官方文档说,context一般可用来传递需要在客户端的返回数据处理函数中用来调用的脚本代码,不过实际上,你传什么都可以,把它看成一种从客户端回调的的激发端,到处理返回数据的接收段之间的参数传递通道就行了。
  2、WebForm_DoCallback(...)
  Ok,明白了以上代码的含义,下面我们来看看,前面的这条“<%= ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context")%>;”在运行时会被解析成什么样子呢?我们只要在页面运行时察看页面源码就可以看到,实际上服务器帮我们生成了下面这段script代码:

<script language="javascript" type="text/javascript">
function any_script_function()
{
WebForm_DoCallback(
'__Page',arg,ReceiveServerData,context,null,false);
}
</script>

  这段代码是什么意思呢?很显然的他调用了一个系统与定义的script函数:WebForm_DoCallback。我们要把这个函数找出来看看它具体为我们干了什么。在运行时的页面源码中,我们很容易可以找到这段脚本的出处。我们注意到有一个script,src="/TestCallbackWeb/WebResource.axd?d=HEcYmh-7_szSIu1D_mHSEw2&amp;t=632661779991718750",这里就定义了WebForm_DoCallback。让我们把它用flashget下载下来,将扩展名改为.js。看看源码吧,没有被混淆的,所以很容易看明白。我这里就只把和callback相关的部分贴出来解释一下,见代码中的注释:

//用于存放所有未完成的callback对象的数组__pendingCallbacks
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;

//回调主函数WebForm_DoCallback
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {

//构造回调参数,回调参数包括了原来页面上的formpostdata和我们传递的目标控件、eventArgument和部分验证信息
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData
+= "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}

//下面实例化XMLHTTP对象,如果浏览器支持XMLHTTP则直接用XMLHTTP 执行异步回调
var xmlRequest,e;
try {
xmlRequest
= new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest
= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists
= (xmlRequest && xmlRequest.setRequestHeader);
}
catch(e) {}
var callback = new Object();
callback.eventCallback
= eventCallback;
callback.context
= context;
callback.errorCallback
= errorCallback;
callback.async
= useAsync;

//获取对应的回调对象
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex]
= null;
}
__synchronousCallBackIndex
= callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange
= WebForm_CallbackComplete;
callback.xmlRequest
= xmlRequest;
xmlRequest.open(
"POST", theForm.action, true);
xmlRequest.setRequestHeader(
"Content-Type", "application/x-www-form-urlencoded");
xmlRequest.send(postData);
return;
}

//万一浏览器不支持XMLHTTP的话,我们IFRAME方案代替,在一个隐藏的 IFRAME中执行Postback
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame
= document.createElement("IFRAME");
xmlRequestFrame.width
= "1";
xmlRequestFrame.height
= "1";
xmlRequestFrame.frameBorder
= "0";
xmlRequestFrame.id
= callbackFrameID;
xmlRequestFrame.name
= callbackFrameID;
xmlRequestFrame.style.position
= "absolute";
xmlRequestFrame.style.top
= "-100px"
xmlRequestFrame.style.left
= "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src
= callBackFrameUrl;
}
}
catch(e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame
= document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write(
"");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write(
'<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[
0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element
= __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type
= "hidden";
fieldElement.name
= element.name;
fieldElement.value
= element.value;
xmlRequestFrame.document.forms[
0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type
= "hidden";
callbackIdFieldElement.name
= "__CALLBACKID";
callbackIdFieldElement.value
= eventTarget;
xmlRequestFrame.document.forms[
0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type
= "hidden";
callbackParamFieldElement.name
= "__CALLBACKPARAM";
callbackParamFieldElement.value
= eventArgument;
xmlRequestFrame.document.forms[
0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type
= "hidden";
callbackValidationFieldElement.name
= "__EVENTVALIDATION";
callbackValidationFieldElement.value
= theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[
0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type
= "hidden";
callbackIndexFieldElement.name
= "__CALLBACKINDEX";
callbackIndexFieldElement.value
= callbackIndex;
xmlRequestFrame.document.forms[
0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[
0].submit();
}
},
10);
}

//该函数在每次回调结束后会调用来检查当前的回调列表中的回调的执行情况,如果,执行完毕的,则从列表中删除回调对象,并删除临时建立的IFRAME
function WebForm_CallbackComplete() {
for (i = 0; i < __pendingCallbacks.length; i++) {
callbackObject
= __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
WebForm_ExecuteCallback(callbackObject);
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex
= -1;
}
__pendingCallbacks[i]
= null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
}
}
}

//该函数执行我们在回调激发端指定的处理返回数据的script函数,如我们上面范例代码中的ReceiveServerData函数
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(
1), callbackObject.context);
}
}
else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(
1), callbackObject.context);
}
}
else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement
= document.createElement("INPUT");
validationFieldElement.type
= "hidden";
validationFieldElement.name
= "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value
= validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex
+ validationFieldLength + 1), callbackObject.context);
}
}
}
}
}

//获取对应的回调对象
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i]
= element;
return i;
}

//再下面是一些辅助函数和与callback关系不大的函数,我就不列出来了,有兴趣的朋友可以自己看看
//
[第1页][第2页]
0
0

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻