繁体   English   中英

将回调 function 作为字符串传递,同时保留 scope 链

[英]Passing a callback function as a string while retaining the scope chain

对于使用 UIWebView 的 iPad 应用程序,我将一个回调 function 传递给 ZE6B3031A8D2C4D854A 中的应用程序:

function query(db, query, callback) {
  var iframe = document.createElement("IFRAME");

  // Filter comments from the callback (as this would break things).
  var callbackstr = "" + callback;
  callbackstr = callbackstr.replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, ''); 

  // Put the query + the callback in an url that will be caught by the iOS app. 
  iframe.setAttribute("src", "ios-query:#iOS#" + query +":#iOS#"+ callbackstr);
  document.documentElement.appendChild(iframe);
  iframe.parentNode.removeChild(iframe);
  iframe = null;    
}

该应用程序从 URL 解析回调 function,并调用回调 function 并通过 stringByEvaluatingJavaScriptFromString 插入一些数据。 这一切都很好。

但是,现在我想在回调 function 中使用闭包,如下所示:

            var callback = function (problemdata) {
                // Return the 'real' callback.
                return function (tx, results) {
                    // Do something with problemdata
                }
            }(problemdataFromScopeChain)

这是有问题的。 由于回调 function 被转换为字符串,所有作用域链信息都丢失了。

关于如何解决这个问题的任何建议?

编辑:

我更喜欢“查询”function 方面的解决方案。 例如:有没有办法将作用域链中的变量转换为 eval()-able 字符串?

与其将回调 function 本身传递给查询页面,不如传递一个与回调数组中的索引对应的 ID?

例如

var callback = function(problemdata){
// Do stuff
};

callbacks = [];
callbacks.append(callback); // so index of 0

现在,您使用回调索引而不是实际的回调 function 提供查询 iframe src

最后,您的查询服务器端脚本可以返回类似的内容

callbacks[0]("this is a load of JSON for example");
var problemdataFromScopeChain = 4;
var callback = function(problemdata){
  // Return the 'real' callback.
  //return function (tx, results) {
  //  // Do something with problemdata
  //  return tx + results + problemdata;
  //}
  return new Function('tx', 'results', 'return tx + results + ' + problemdata + ';');
}(problemdataFromScopeChain);
alert('' + callback);

但在我看来,像这样使用 Function 构造函数不是很好 =)。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM