Skip to content Skip to sidebar Skip to footer

Synchronizing Event-based Plugin Calls In Javascript

I'm writing some JavaScript that interacts with a browser plugin (add-on in Firefox, ActiveX in IE). Some of the calls are asynchronous and trigger an event when complete. There

Solution 1:

Why do you say Deferreds don't fit with callbacks? It seems to me that

pluginObject.disconnectDevice(deviceKey).then(function() { 
    pluginObject.connectDevice(deviceKey, backingInfo);
});

reads pretty natural.

If you can't change the plugin code, you can still use this approach, but of course you'll have to wrap the plugin in some sort of API adapter. Basically, each call to disconnectDevice in your wrapper would create a Deferred, register it in a queue and return it. When you receive the disconnection event, you resolve all pending deferreds in order (be careful with re-entrance).

You'd need to do this for every event fired by the plugin that you want to handle.

The deferred approach has the benefit of improved code readability and maintainability IMHO (over the event listener API).

Solution 2:

Can't you just add a callback to disconnectDevice and pass in the call to connectDevice?

pluginObject.disconnectDevice = function ( key, callback ) {
    // do stuff and then when disconnect complete...callback();
};

...then when you want to attach a device...

pluginObject.disconnectDevice(deviceKey, function() {
    pluginObject.connectDevice(deviceKey, backingInfo);
});

Solution 3:

Assuming you set the handler with a simple property called onConnectionChange, you can write a new function that takes a callback instead.

// The new function, it takes a callback to let you know// that disconnecting is done
pluginObject.disconnect = function (deviceKey, callback) {
     var me = this;
     me.onConnectionChange = function (connectionState) {
        if (connectionState === state.disconnected) {
             delete me.onConnectionChange;
             callback();
        }
}

// Now you can call
pluginObject.disconnect(deviceKey, function() {
    pluginObject.connectDevice(deviceKey, backingInfo);
});

Post a Comment for "Synchronizing Event-based Plugin Calls In Javascript"