Jacob Jacob - 19 days ago 7
jQuery Question

JavaScript same functions, different implementation decided on runtme

What is the best way to change JavaScript implementations at run time?

I have a web application which connects to the server by SignalR.

If there is any problem connecting to the server using SignalR at runtime, I want to change the services functions implementations to work with regular XHR.

I have one js file with the following functions to connect via SignalR:

function initializeConnection() {
// Initialize connection using SignalR
}

function sendEcho() {
// Sending echo message using signalR
}


And another js file with the same functions for connection via XHR:

function initializeConnection() {
// Initialize connection using XHR
}

function sendEcho() {
// Sending echo message using XHR
}


I know it is impossible to have them loaded at the same time.

I know I can use one file with a toggle within each function.

I thought maybe I can switch between these files by loading & unloading them at runtime. Is this possible? If so, is this the best way for such an issue?

What is the best way for supplying different implementations at runtime?

Answer

One way to do it, is to define both implementations as objects with same signatures and just set the namespace to a variable:

;var MyStuff = {
    //SignalR
    SignalR: {
        initializeConnection: function(){console.log('SignalR.initializeConnection()')},
        sendEcho: function(){console.log('SignalR.sendEcho()')}
    },

    //XHR
    XHR: {
        initializeConnection: function(){console.log('XHR.initializeConnection()')},
        sendEcho: function(){console.log('XHR.sendEcho()')}
    }
};

//Do whatever check you want to
var mNamespace = (1 === 2) ? MyStuff.SignalR : MyStuff.XHR;

//Call the instance
mNamespace.initializeConnection();

You can also keep them split in two files and add them both to MyStuff dynamicallly:

//File 1
;var MyStuff = (MyStuff === undefined) ? {} : MyStuff;
MyStuff.SignalR = {..};

//File 2
;var MyStuff = (MyStuff === undefined) ? {} : MyStuff;
MyStuff.XHR = {..};