2012-03-06 58 views
2

我正在寫一些JavaScript後端代碼,並計劃使用GUI的本地代碼。這在Android中完全正常,但是我在Mac OS X上的Cocoa中遇到了一些問題。我已經遵循關於此問題的Apple教程,但它不起作用。讓我在看完代碼後嘗試解釋這一點。將obj-c類傳遞給javascript不起作用。我究竟做錯了什麼?

的Index.html

<html> 
<head> 
    <script type="text/javascript"> 
     document.addEventListener("DOMContentLoaded", ready, false); 

     function ready() { 
      document.write(returnString()); 
      bridge.onBackendReady(); 
     } 

     function returnString() { 
      return "Hello World!!!!"; 
     } 
    </script> 
</head> 
<body> 

</body> 
</html> 

AppDelegate.m

#import "AppDelegate.h" 
#import "BackendBridge.h" 


@implementation AppDelegate 

@synthesize webview; 
@synthesize backend; 


-(void)applicationDidFinishLaunching:(NSNotification *)notification 
{ 
backend = [[BackendBridge alloc] init]; 

NSString *backendPath = [[NSBundle mainBundle] pathForResource:@"Index" ofType:@"html"]; 
NSURL *backendUrl = [NSURL fileURLWithPath:backendPath]; 

[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:backendUrl]]; 
[[webview windowScriptObject] setValue:backend forKey:@"bridge"]; 
} 

@end 

BackendBridge.m

#import "BackendBridge.h" 


@implementation BackendBridge 

-(void)onBackendReady 
{ 
NSLog(@"Ready"); 
} 

@end 

所以,我想在這裏做的是相當簡單的。在javascript中調用BackendBridge類中的onBackendReady函數。從Apple WebView api和tutorial中我可以理解的,這應該是正確的方法,但它不起作用(NSLog調用不運行)。我知道,JavaScript函數按預期工作,在我的UI我可以看到字符串「Hello World !!!!」 ......

+0

您指的是哪個Apple文檔? – ThomasW 2012-03-06 08:44:30

+0

另外,你知道'applicationDidFinishLaunching:'方法是否被調用嗎? – ThomasW 2012-03-06 08:46:09

回答

2

WebScriptObject.h的評論說:

By default, no properties or functions are exported. A class must implement 
+isKeyExcludedFromWebScript: and/or +isSelectorExcludedFromWebScript: to 
expose selected properties and methods, respectively, to JavaScript. 

也許添加此到BackendBridge

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector 
{ 
    return selector != @selector(onBackendReady); 
} 
+0

Kurt!很高興在這裏見到你。 – ThomasW 2012-03-06 08:53:23

-1

bridge_onBackendReady();

使用下劃線代替。或者:

+0

它是下劃線而不是:...替換。使用_會非常非常錯誤,因爲onBackendReady是橋對象的屬性(更精確的是window.bridge對象),而不是選擇器。 – 2012-03-16 09:40:27

相關問題