Commits

Matthew Schinckel  committed 7250db6

Handle callbacks being passed in to read/write handlers.

  • Participants
  • Parent commits 85f5276

Comments (0)

Files changed (1)

File src/garmin.js

       return devices[currentDevice];
     };
             
-    var baseHandler = function(readWrite, dataType, pluginMethod, name) {
+    var baseHandler = function(readWrite, dataType, pluginMethod, name, callback) {
       if (devices.length === 0) {
         send('interactionError', {message: "No devices found."});
       }
         var status = plugin['Finish' + readWrite + pluginMethod]();
         switch (status) {
           case Garmin.STATUS.working:
-            send('progressInterationWithDevice', {device: device, progress: getProgress(), status: status});
+            send('progressInterationWithDevice', {
+              device: device, 
+              progress: getProgress(), 
+              status: status
+            });
             setTimeout(finishHandler, 200);
             break;
           case Garmin.STATUS.finished:
             send('endInteractionWithDevice', {device:device, status: status});
             send(readWrite.toLowerCase() + name + 'Complete', {device:device, data:plugin.TcdXml});
             inUse = false;
+            // If we were passed in a callback function, we call it with either the data
+            // we got from the plugin, or true (on a write).
+            if (callback) {
+              callback(plugin.TcdXml || true);
+            }
             break;
           case Garmin.STATUS.waiting:
             send('awaitingUserInput', {});
     };
     
     var readHandler = function(dataType, pluginMethod, type) {
-      return function(){
+      return function(callback){
         // Empty the data store, so we don't get bogus data if the event cannot complete.
         plugin.TcdXml = "";
-        baseHandler('Read', dataType, pluginMethod, type);
+        baseHandler('Read', dataType, pluginMethod, type, callback);
       };
     };
     
     var writeHandler = function(dataType, pluginMethod, type) {
-      return function(data, filename) {
+      return function(data, filename, callback) {
         // Strip out any newlines, as they break things.
         plugin.TcdXml = data.replace(/[\n\r]+/gm, '');
         plugin.FileName = filename;
-        baseHandler('Write', dataType, pluginMethod, type);
+        baseHandler('Write', dataType, pluginMethod, type, callback);
       };
     };
     
     unlock(_.union(unlockCodes, delegate.unlockCodes || []));
     
     // wait for other initialisation to finish, then search for devices.
-    if (autostart) {
+    if (autostart || !delegate) {
       setTimeout(this.findDevices, 0);
     }
   };