Reputation: 578
I'm using an Ionic/Cordova plugin to watch a data set and want to call a function in my typescript class when the native api triggers an event. What I have so far is: (Typescript file)
this.platform.ready().then(() =>{
window.plugins.plugin.startFileWatch("Path", (success) =>{console.log("Succes")}, (error) => {Console.log("ERROR"}))
}
and then in java script from the plugin
startFileWatch: function( path, succesCB, errorCB){
exec(succesCB, errorCB, "Class", "startFileWatch", [path]);
}
and in swift (though android solutions are welcome aswell):
@objc(startFileWatch:)
func startFileWatch(command:CDVInvokedUrlCommand){
//bit pseudo here
something.addListener{
self?.commandDelage.send(result, callbackID: command.callbackID)
}
}
this however didn't work
Upvotes: 0
Views: 1081
Reputation: 570
Your TS and JS script looks good. And what you are missing is that, you are not saving the callback for future triggers. To trigger a dynamic event from Native to TS, you need to have a listener which will actually register a callback in native layer. Then this callback is used to push event to TS layer.
// Android
protected static CallbackContext eventTriggerObj = null;
.....
.....
private boolean registerForEvents ( final CallbackContext callbackContext )
{
eventTriggerObj = callbackContext;
return true;
}
// iOS ( Obj C )
@property ( nonatomic, retain ) NSString * eventTriggerObj ;
.....
.....
- ( void ) registerForEvents :( CDVInvokedUrlCommand * ) command
{
self.eventTriggerObj = command.callbackId;
CDVPluginResult * pluginResult = [ CDVPluginResult
resultWithStatus:CDVCommandStatus_OK ];
[ pluginResult setKeepCallbackAsBool:true ];
[ self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId ];
}
// Swift Code (3+)
private var eventTriggerObj : String
void registerForEvent(command : CDVInvokedUrlCommand){
self.eventTriggerObj = command.callbackId
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: ["Message"])
pluginResult?.keepCallback = true
self?.commandDelegate.send(pluginResult, callbackId: self?.eventTriggerObj)
}
Now use the callback object eventTriggerObj to send the dynamic events to the TS Layer.
Upvotes: 1