JavaScript same functions, different implementations decided on runtme

What is the best way to change JavaScript implementations at runtime?

I have a web application that connects to a server using SignalR .
If there is any problem connecting to the server using SignalR at runtime, I want to change the implementation of the services functions 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 connecting via XHR :

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

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

I know that they cannot be downloaded at the same time. I know that I can use one file with a switch inside each function.

, , , , . ? , ?

?

+4
2

- :

;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();

MyStuff dynamicallly:

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

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

, , - " " " ". ( ) . , , .

"" , -.

:

var sendMessage = function() {
  // Perform a check, or try a first message using your default connection flavour
  // Depending on the result, redefine the function accordingly
  sendMessage = sendMessageUsingWhatever;
};

//Use sendMessage anywhere you want, it'll use the proper protocol
Hide result

:

var addHandler = document.body.addEventListener ?
  function(target, eventType, handler) {
    target.addEventListener(eventType, handler, false);
  } :
  function(target, eventType, handler) {
    target.attachEvent("on" + eventType, handler);
  };
Hide result

, ( ) .

. , , , , .

, , , .

+1

Source: https://habr.com/ru/post/1661453/


All Articles