4、研究DWR 因为06年使用DOJO+DWR(1.0)的时候,已经遇到过这个问题,当时没做太多功课,直接改了dwr的源代码。 现在用dwr2,于是想先看看DWR是不是对这个问题有新的处理方式, 将dwr.jar中的engine.js拿出来,查看了有关回调的相关代码(_remoteHandleCallback和_execute), 发现对回调的处理方式似乎比1.0更简单,没办法将对象和方法一起传过去。 5、做进一步的研究 因为这次DWR在项目中的使用太广泛,而且我相信这样的需求应该是可以满足的,于是没有立刻修改源码, 首先,在Google上搜Dojo+dwr,没有查到什么结论,可能Dojo的用户不是太多。 于是又搜”javascript callback object context“,得到一篇文章专门介绍java回调函数的问题: http://bitstructures.com/2007/11/javascript-method-callbacks 最重要的一句话: When a function is called as a method on an object (obj.alertVal()), "this" is bound to the object that it is called on (obj). And when a function is called without an object (func()), "this" is bound to the JavaScript global object (window in web browsers.) 这篇文章也提供了解决方案,就是使用Closure和匿名方法, 在javascript中,在function内部创建一个function的时候,会自动创建一个closure, 而这个closure就能记住对应的function创建时的上下文。 所以,如果这样: JScript code var closureFunc=function(){ testObj.callback(); } 那么无论在什么地方,直接调用closureFunc()和调用testObj.callback()是等价的。 详情参见上面提到的文章:http://bitstructures.com/2007/11/javascript-method-callbacks。 6、改进模拟代码 模拟代码只,我们再增加一种回调方式: JScript code 复制代码 代码如下: <html> <head> <script type="text/javascript"><!-- var context="全局"; var testObj={ context:"初始", callback:function (str){ //回调函数 alert("callback:我所处的上下文中,context="+this.context+",我被回调的方式:"+str); } }; //创建一个对象,作为测试回调函数的上下文 function testCall(){ callMethod(testObj.callback); callWithClosure(function(param){testObj.callback(param);}); testObj.context="已设置"; callObjMethod(testObj,testObj.callback); } function callMethod(method){ method("通过默认上下文回调"); } function callWithClosure(method){ method("通过Closure保持上下文回调"); } function callObjMethod(obj,method){ method.call(obj,"指定显式对象上下文回调"); } // --></script> </head> <body> <a href="javascript:void(0)" onclick="testCall()">调用测试</a> </body> </html>
function callObjMethod(obj,method){method.call(obj,"指定显式对象上下文回调"); } function callMethod(method){ method("通过默认上下文回调"); } function callWithClosure(method){ method("通过Closure保持上下文回调"); } function callback(str){ alert("callback:我是定义在外部的全局函数。"); } // --></script> </head> <body> <a href="javascript:void(0)" onclick="testCall()">调用测试</a> </body> </html>
8、什么是Closure Two one sentence summaries: a closure is the local variables for a function - kept alive after the function has returned, or a closure is a stack-frame which is not deallocated when the function returns. (as if a "stack-frame" were malloc"ed instead of being on the stack!)