2013-08-30 34 views
0

我知道github上有很多phonegap/cordova插件的例子,但是我看到插件的構建方式存在很多不一致之處。結構看起來一樣(大部分),但代碼和實現幾乎每一個都不相同。這讓我問了幾個問題。Phonegap/Cordova 2.9自定義插件創建。任何工作示例?

  • 2.9文檔說使用在配置中聲明插件的方法,但我得到構建警告說,使用該方法。我應該同時使用嗎?

  • 在javascript中,聲明/實例化插件的正確方法是什麼?

  • 我是通過window.MyPlugin.myMethod引用我的插件的方法還是僅僅是window.myMethod?

我有更多的問題,但代碼將是驚人的。

有沒有人有一個絕對簡單的例子爲科爾多瓦2.9,爲iOS平臺,定製插件工作?

回答

1

這是一個非常簡單的插件,我寫了幾天去了,它只是測試構建一個基於iOS的Cordova插件。

JS:

var tester = function() {}; 

tester.prototype.test = function() { 
    cordova.exec(
     function(result) { 
      navigator.notification.alert('test plugin returned: '+result); 
     }, 
     function() { 
      navigator.notification.alert('test plugin error'); 
     }, 
     'TestPlugin', 
     'test', 
     ['Your test string'] 
    ); 
}; 

if(!window.plugins) { 
    window.plugins = {}; 
} 
if (!window.plugins.tester) { 
    window.plugins.tester = new tester(); 
} 

與被叫:

<button onclick="window.plugins.tester.test()">TEST PLUGIN</button> 

TestPlugin.h:

#import <Cordova/CDV.h> 

@interface TestPlugin : CDVPlugin 

- (void)test:(CDVInvokedUrlCommand*)command; 

@end 

TestPlugin.m:

#import "TestPlugin.h" 
#import <Cordova/CDV.h> 

@implementation TestPlugin 

- (void)test:(CDVInvokedUrlCommand*)command 
{ 
    CDVPluginResult* pluginResult = nil; 
    NSString* testString = [command.arguments objectAtIndex:0]; 

    if (testString != nil && [testString length] > 0) { 
     pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:testString]; 
    } else { 
     pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; 
    } 

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; 
} 

@end 

已添加到/platforms/ios/{PROJECT_NAME}/Resources/config.xml中:

<plugin name="TestPlugin" value="TestPlugin" /> 
+0

首先,這是一個很好的回覆。我非常感謝簡潔而全面的代碼。謝謝。我遇到了同樣的問題,我一直在摔跤幾天。當我點擊該測試按鈕時,沒有任何反應。也許我不是在正確的地方尋找錯誤。儘管如此,控制檯中似乎沒有任何東西出現。有任何想法嗎? – QuailAndQuasar