簡體   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